问题
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