Loading CLR in C++, Start() problem

大城市里の小女人 提交于 2019-12-11 02:42:48

问题


So I'm trying to load up the .NET 4 runtime and run my own C# DLL. The Start() method is throwing a HRESULT=0x1 error. If I comment out the start code, the C# DLL loads and executes, then the Stop() method throws a HRESULT=0x8000ffff error. I've looked for hours and all the code looks like what I have below (I left out all my debugging/error handling). Thank you very much for any tips in advance! =)

    void DotNetLoad()
    {
        ICLRRuntimeHost *pClrHost = NULL;
        ICLRMetaHost *lpMetaHost = NULL;
        MessageBox(0, L"Creating CLR instance.", L"Bootstrap Message", 0);
        HRESULT hr = CLRCreateInstance(
            CLSID_CLRMetaHost,
            IID_PPV_ARGS(&lpMetaHost));
        ICLRRuntimeInfo *lpRuntimeInfo = NULL;
        hr = lpMetaHost->GetRuntime(L"v4.0.30319",
            IID_PPV_ARGS(&lpRuntimeInfo));
        hr = lpRuntimeInfo->GetInterface(
            CLSID_CLRRuntimeHost,
            IID_ICLRRuntimeHost,
            (LPVOID *)&pClrHost);
        hr = pClrHost->Start();
        DWORD dwRet = 0;
        hr = pClrHost->ExecuteInDefaultAppDomain(
            pwzTargetDll,
            pwzNamespaceClass, pwzFunction, L"pwzArgument", &dwRet);
        hr = pClrHost->Stop();
        hr = pClrHost->Release();

    }

I understand the bit about decoupling the init, .NET call, and deinit, but what do you mean by app startup and shutdown? Right now I have DotNetLoad being called from a DLL method that is injected into a remote process. Basically:

extern "C" __Declspec(dllexport) void Initialize()
{
    DotNetLoad(params); //ex.
}

回答1:


By combining runtime init with the assembly method call, followed by runtime deinit, you are executing this code on every call to DotNetLoad().

See the important block here -- http://msdn.microsoft.com/en-us/library/ms164416.aspx This leads me to believe that once you load the runtime into your process you don't want to do it again.

Split your initialization / deinitialization OUT of the method used to call the .NET assembly. Do the initialization only once (at app startup and prior to making the call), and do the deinitialization only once (at app shutdown). I tested this and it worked without error.



来源:https://stackoverflow.com/questions/6605391/loading-clr-in-c-start-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!