我正在尝试将托管 c# dll 注入本机可执行文件。我将以下代码注入可执行文件以加载 CLR。
我知道注入有效,因为当我将代码注入 cmd.exe 时,它会正确输出。我知道CLRCreateInstance、pMetaHost->GetRuntime、pRuntimeInfo->GetInterface都返回 S_OK,但pClrRuntimeHost->Start()返回 E_FAIL。
这只发生在我将 dll 注入远程进程时。如果我在自己的进程中加载 dll 并从那里调用 Main,所有调用都返回 S_OK 并且托管代码运行良好。
更新:我尝试将代码注入其他进程,如 notepad.exe 和 explorer.exe。它在那些运行良好。我仍然很好奇它为什么不在 cmd.exe 中运行,但我只是将它用于测试目的,所以它不再是问题了。
GetLastError 返回“试图引用不存在的令牌”
#include "stdafx.h"
#include "Bootstrap.h"
#include <metahost.h>
#pragma comment(lib, "mscoree.lib")
using namespace std;
//Forward declarations
void StartTheDotNetRuntime();
DllExport HRESULT Main(_In_ LPCTSTR lpCommand)
{
cout << "Starting .NET runtime" << endl;
StartTheDotNetRuntime();
return 0;
}
void StartTheDotNetRuntime()
{
wprintf(L"Press enter to load the .net runtime...");
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();
cout << "RESULT: " << hr << endl;
wprintf(L".Net runtime is loaded.");
// Okay, the CLR is up and running in this (previously native) process.
// Now call a method on our managed C# class library.
DWORD dwReturn = 0;
hr = pClrRuntimeHost->ExecuteInDefaultAppDomain(
L"F:\\Client.dll",
L"Client.Main", L"Start", L"MyParameter", &dwReturn);
cout << dwReturn << endl;
}