问题
I have written a c# program that calls a c++ dll that echoes the commandline args to a file
When the c++ is called using the rundll32 command it displays the commandline args no problem, however when it is called from within the c# it doesnt.
I asked this question to try and solve my problem, but I have modified it my test environment and I think it is worth asking a new question.
Here is the 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;
}
Here is the 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();
}
}
}
The output from the rundll32 command is
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"
however the output when the c# app runs is
/
回答1:
LPCSTR
is not unicode, is it? Just use ANSI and you should be fine: CharSet = CharSet.Ansi
来源:https://stackoverflow.com/questions/2621066/calling-unmanaged-dll-from-c-take-2