DLL с точкой входа - C#
Формулировка задачи:
Хочу сделать библу, чтобы при подгрузке выполнялась главная функция. Так же как в С++ DllMain().
Библиотека будет загружаться в сторонний процесс специальным инжектором. Много чего перерыл.
Решение задачи: «DLL с точкой входа»
textual
Листинг программы
// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include <metahost.h>
#include <mscoree.h>
#pragma comment(lib, "mscoree.lib")
ICLRRuntimeHost* GetRuntimeHost(LPCWSTR dotNetVersion)
{
ICLRMetaHost* metaHost = NULL;
ICLRRuntimeInfo* info = NULL;
ICLRRuntimeHost* runtimeHost = NULL;
// Get the CLRMetaHost that tells us about .NET on this machine
if (S_OK == CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID*)&metaHost))
{
// Get the runtime information for the particular version of .NET
if (S_OK == metaHost->GetRuntime(dotNetVersion, IID_ICLRRuntimeInfo, (LPVOID*)&info))
{
// Get the actual host
if (S_OK == info->GetInterface(CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (LPVOID*)&runtimeHost))
{
// Start it. This is okay to call even if the CLR is already running
runtimeHost->Start();
}
}
}
if (NULL != info)
info->Release();
if (NULL != metaHost)
metaHost->Release();
return runtimeHost;
}
int ExecuteClrCode(ICLRRuntimeHost* host, LPCWSTR assemblyPath, LPCWSTR typeName,
LPCWSTR function, LPCWSTR param)
{
if (NULL == host)
return -1;
DWORD result = -1;
if (S_OK != host->ExecuteInDefaultAppDomain(assemblyPath, typeName, function, param, &result))
return -1;
return result;
}
void execute()
{
ICLRRuntimeHost* host = GetRuntimeHost(L"v4.0.30319");
ExecuteClrCode(host , L"C:\\ClassLibrary1.dll", L"ClassLibrary1.Class1", L"Main", L"");
// At some point you will need to call Release(). You can do it now or during cleanup code
host->Release();
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)execute, NULL, NULL, NULL);
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}