Loading mixed mode assembly from unmanaged code

爷,独闯天下 提交于 2019-12-07 17:07:43

问题


As the title says i want to call a mixed mode assembly from unmanaged code.

To be more precise, i want to load the mixed mode assembly dynamically and then execute some static unmanaged startup code that registers some Managed C++ Wrappers for C# Code.

Is this possible (or do i need to embed the .Net Runtime or use COM?) ?

Has anybody already done this and can share some experience?

PS: If the mixed mode assembly contains a WPF Window will it be started?


回答1:


You need to get the CLR loaded and initialized. Yes, making a managed class [ComVisible] or hosting the CLR yourself with CorBindToRuntimeEx() is a way to do this. A very simple way is to export a managed function from your DLL, the C++/CLI compiler embeds a thunk in the code that takes care of initializing the CLR. Very easy to do but it does not scale well when the interface to your managed code is fat.

ref class Bootstrap
{
public:
    static void Initialize() { 
        // etc..
    }
};

extern "C" __declspec(dllexport) 
void __stdcall LoadAndInitialize()
{
    Bootstrap::Initialize();
}

You could embellish by passing a function pointer to your native interface. Convert it to a managed delegate with Marshal::GetDelegateForFunctionPointer(). Don't forget to wrap any native declarations with #pragma managed if you do this.



来源:https://stackoverflow.com/questions/6110820/loading-mixed-mode-assembly-from-unmanaged-code

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