Could not figure out how to call a function in managed dll file using the unmanaged dll.
Currently,I was able to inject an unmanaged dll into a running process and calling an managed dll(and to mention mainly i am a newbie to c++) using that as shown below.
#include "stdafx.h"
#include <Windows.h>
#include "dllmain.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved )
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
LoadManagedProject(L"C:\\Users\\nagaganesh.kurcheti\\Desktop\\ExampleProject.dll");
DisplayPid();
break;
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
void DisplayPid()
{
DWORD pid = GetCurrentProcessId();
wchar_t buf[64];
wsprintf(buf, L"Hey, it worked! Pid is %d", pid);
MessageBox(NULL, buf, L"Injected NEW MessageBox", NULL);
}
AND FROM DLL MAIN I AM CALLING A FUNCTION THAT HANDLES THE INJECTION PROCESS THAT LOOK LIKE:-
DllExport void LoadManagedProject(const wchar_t * managedDllLocation)
{
HRESULT hr;
ICLRMetaHost* pClrMetaHost = NULL;
ICLRRuntimeInfo* pClrRuntimeInfo = NULL;
ICLRRuntimeHost* pClrRuntimeHost = NULL;
hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID*)&pClrMetaHost);
if (hr == S_OK)
{
hr = pClrMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&pClrRuntimeInfo));
if (hr == S_OK)
{
BOOL fLoadable;
hr = pClrRuntimeInfo->IsLoadable(&fLoadable);
if ((hr == S_OK) && fLoadable)
{
hr = pClrRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost,
IID_PPV_ARGS(&pClrRuntimeHost));
if (hr == S_OK)
{
hr = pClrRuntimeHost->Start();
if (hr == S_OK)
{
MessageBox(NULL, L"HR=SOK45STTIME", L"Injected MessageBox", NULL);
DWORD result;
hr = pClrRuntimeHost->ExecuteInDefaultAppDomain(
managedDllLocation,
L"ExampleProject.Example",
L"EntryPoint",
L"Argument",
&result);
if (hr == S_OK)
{
MessageBox(NULL, L"HR=SOK6STTIME", L"Injected MessageBox", NULL);
}
}
}
}
}
}
}
I was not able to inject this process after a number of tries . Can i get what mistake that i have made or suggest any better approach of calling a managed dll(c# ) using unmanaged dll that is injected to a running process. Thank you in advance.
UPDATE :
If it is not possible this way , could you suggest any best approach of injecting managed dll into a running process. Thank you
You can achieve this by injecting managed dll into unmanaged process using EasyHook here is sample code:
Or you can find more details at original source