How do I call C++/CLI (.NET) DLLs from standard, unmanaged non-.NET applications?

蹲街弑〆低调 提交于 2019-11-30 19:19:15

Do you use C++/CLI because you want to, or because you think you have to to export functions?

In case of the latter, check out my unmanaged exports, which allows you to declare unmanaged exports in C# equivalent to how DllImport works.

internal class Sample
{
  [DllExport("_export_test", CallingConvention.Cdecl)]
  static int Test(int a)
  {
     return a + 1;
  }
}

Well, the C++/CLI compiler makes it pretty easy. Just write a static managed function and attribute it with __declspec(dllexport). The compiler injects a stub that automatically loads the CLR to execute the managed code.

That's a serviceable approach, it isn't very extensible and it won't be very fast. The next step up is that you write a ref class with the [ComVisible(true)] attribute. After registering it with Regasm.exe, any unmanaged COM aware client can use that server. Hosting the CLR yourself (CorBindToRuntimeEx) is usually the last choice, but the most universal one.


Example code:

ref class ManagedClass {
public:
  static void StaticFunc() {}
};

extern "C" __declspec(dllexport)
void __stdcall UnmanagedFunc() {
  ManagedClass::StaticFunc();
}

This CodeProject article explains the process pretty well.

Using managed code in an unmanaged application
http://www.codeproject.com/KB/mcpp/ijw_unmanaged.aspx

See also here and here.

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