我正在尝试按照本教程将托管 C# dll 加载到托管 C# 进程中。我已经用 C/C++ 编写了相当多的代码,并且具有 MS COM 的工作知识,但是 C# 和托管代码对我来说是一个全新的野兽,所以如果我做错了什么,请原谅我。我的系统上有 .NET 4.5,这是默认使用的相同运行时(我认为)。到目前为止的代码(主要从上面的链接复制):
代码 - C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace InjectSample
{
public class Program
{
int EntryPoint(String pwzArgument)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show(
"I am a managed app.\n\n" +
"I am running inside: [" +
System.Diagnostics.Process.GetCurrentProcess().ProcessName +
"]\n\n" + (String.IsNullOrEmpty(pwzArgument) ?
"I was not given an argument" :
"I was given this argument: [" + pwzArgument + "]"));
return 0;
}
static void Main(string[] args)
{
Program prog = new Program();
prog.EntryPoint("hello world");
}
}
}
本机代码
#include <metahost.h>
#pragma comment(lib, "mscoree.lib")
#import "mscorlib.tlb" raw_interfaces_only \
high_property_prefixes("_get","_put","_putref") \
rename("ReportEvent", "InteropServices_ReportEvent")
#include <strsafe.h>
void ErrorExit(LPCWSTR lpszFunction, DWORD dwLastError)
{
if(dwLastError == 0) return;
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dwFlag = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
FormatMessage( dwFlag, NULL, dwLastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL );
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("%s failed with error %d: %s"), lpszFunction, dwLastError, lpMsgBuf);
::MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
int wmain(int argc, wchar_t* argv[])
{
HRESULT hr;
ICLRMetaHost *pMetaHost = NULL;
ICLRRuntimeInfo *pRuntimeInfo = NULL;
ICLRRuntimeHost *pClrRuntimeHost = NULL;
// build runtime
hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&pMetaHost));
hr = pMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&pRuntimeInfo));
hr = pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost,
IID_PPV_ARGS(&pClrRuntimeHost));
// start runtime
hr = pClrRuntimeHost->Start();
// execute managed assembly
DWORD pReturnValue;
SetLastError(0);
hr = pClrRuntimeHost->ExecuteInDefaultAppDomain(
L"C:\\Temp\\InjectSample.exe",
L"InjectExample.Program",
L"int EntryPoint(String pwzArgument)",
L"hello .net runtime",
&pReturnValue);
ErrorExit(L"ExecuteInDefaultAppDomain()", GetLastError());
// free resources
pMetaHost->Release();
pRuntimeInfo->Release();
pClrRuntimeHost->Release();
return 0;
}
问题
现在的问题是,当我执行本机代码时,GetLastError()
返回0
. 那是在调用之后ExecuteInDefaultAppDomain()
。根据 Codeproject 链接,它应该显示对话框,但在我的情况下它没有显示任何内容。
我不确定这个问题,任何建议/指针都会有所帮助。谢谢。