从C#调用非托管dll。拿2

时间:2010-04-12 09:47:34

标签: c# c++ dll unmanaged managed

我编写了一个调用c ++ dll的c#程序,它将命令行args与文件相呼应

当使用rundll32命令调用c ++时,它显示命令行args没问题,但是当它从c#中调用时它不会。

I asked this question尝试解决我的问题,但我已将其修改为我的测试环境,我认为值得提出一个新问题。

这是c ++ dll

#include "stdafx.h"
#include "stdlib.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;

BOOL APIENTRY DllMain( HANDLE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    return TRUE;
}

extern "C" __declspec(dllexport) int WINAPI CMAKEX(
    HWND hwnd,
    HINSTANCE hinst,
    LPCSTR lpszCommandLine,
    DWORD dwReserved)
{

    ofstream SaveFile("output.txt");
    SaveFile << lpszCommandLine;
    SaveFile.close();

    return 0;
}

这是c#app

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Net;

namespace nac
{
    class Program
    {
        [DllImport("cmakca.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        static extern bool CMAKEX(IntPtr hwnd, IntPtr hinst, string lpszCmdLine, int nCmdShow);

        static void Main(string[] args)
        {
            string cmdLine = @"/source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp""";
            const int SW_SHOWNORMAL = 1;
            CMAKEX(IntPtr.Zero, IntPtr.Zero, cmdLine, SW_SHOWNORMAL).ToString();
        }
    }
}

rundll32命令的输出是

rundll32 cmakex.dll,CMAKEX /source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp"

/source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp"

然而,c#app运行时的输出是

/

1 个答案:

答案 0 :(得分:2)

LPCSTR不是unicode,是吗?只需使用ANSI即可,您应该没问题:CharSet = CharSet.Ansi