views:

217

answers:

1

I am exploring calling .net methods from unmanaged C++ code and have found the function below in How To Inject a Managed .NET Assembly (DLL) Into Another Process

void StartTheDotNetRuntime()
{
    // Bind to the CLR runtime..
    ICLRRuntimeHost *pClrHost = NULL;
    HRESULT hr = CorBindToRuntimeEx(
        NULL, L"wks", 0, CLSID_CLRRuntimeHost,
        IID_ICLRRuntimeHost, (PVOID*)&pClrHost);

    // Push the CLR start button
    hr = pClrHost->Start();

    // Okay, the CLR is up and running in this (previously native) process.
    // Now call a method on our managed class library.
    DWORD dwRet = 0;
    hr = pClrHost->ExecuteInDefaultAppDomain(
        L"c:\\PathToYourManagedAssembly\\MyManagedAssembly.dll",
        L"MyNamespace.MyClass", L"MyMethod", L"MyParameter", &dwRet);

    // Stop the CLR runtime
    hr = pClrHost->Stop();

    // Don't forget to clean up.
    pClrHost->Release();
}

This works with no problem when called once in a console application.

I now want to split this function for use within a dll, logically this should be in three parts

Method - DLLMain
    DLL_PROCESS_ATTACH
         Bind to the CLR runtime
         Push the CLR start button

    DLL_PROCESS_DETACH
         Stop the CLR runtime
         Do not forget to clean up.

Method - CallDotNetToDoSomething

How and where do I declare the ICLRRuntimeHost pClrHost/HRESULT hr in order to achieve this?

A: 

They should likely be global (static) variables, or in a singleton of some sort. There is only one .NET runtime allowed per process (at least these days), so there is little sense in trying to be a whole lot more clever than that. Populate the globals in DLL load, then depopulate them during DLL unload.

For a .NET/Mono embedding project I did, I created an object whose constructor booted up the runtime (i.e. bind/push start button) and whose destructor shut it down (stop/release). This way the main application could choose how to operate, i.e. put it on the stack in main(), or do a new() during DLL load, and delete in DLL unload. In that case, the pointers you mention would be instance variables of a new object you create, e.g. ClrEmbedManager. That's overkill if your library doesn't need to be reused in different kinds of applications with different behaviors.

Sebastian Good