【问题标题】:Calling unmanaged dll from C#. Take 2从 C# 调用非托管 dll。拿 2
【发布时间】:2011-02-06 22:37:24
【问题描述】:

我编写了一个 c# 程序,它调用一个 c++ dll,它将命令行参数回显到一个文件中

当使用 rundll32 命令调用 c++ 时,它显示命令行参数没有问题,但是当从 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# 应用程序

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#应用运行时的输出是

/

【问题讨论】:

    标签: c# c++ dll unmanaged managed


    【解决方案1】:

    LPCSTR 不是 unicode,是吗?只需使用 ANSI 就可以了:CharSet = CharSet.Ansi

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 2013-01-07
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 2010-12-17
      相关资源
      最近更新 更多