Embedding a managed dll in a native process

I am trying to embed a managed C # dll in my own executable. I load the following code into an executable to load the CLR.

I know that injection works, because when I enter the code in cmd.exe, it displays correctly. I know that CLRCreateInstance, pMetaHost-> GetRuntime, pRuntimeInfo-> GetInterface all return S_OK, but pClrRuntimeHost-> Start () returns E_FAIL.

This only happens when I insert the dll into the remote process. If I load the DLL into my own process and call Main, all calls return S_OK, and the managed code works fine.

Update: I tried to paste the code into other processes, such as notepad.exe and explorer.exe. Everything is fine in them. I'm still wondering why it does not start in cmd.exe, but I used it only for testing, so this is no longer a problem.

GetLastError returns "An attempt was made to reference a token that does not exist"

#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; } 
+2
source share
1 answer

I found the answer to the problem, at least for me, the process into which the bootstrap is loaded requires administrator rights. It took me a long time to understand that for all programs I have administrator rights, and as soon as I started the process, I entered it as an administrator, it will work!

0
source

Source: https://habr.com/ru/post/1244800/


All Articles