开发者

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

In the unmanaged world, I was able to write a __declspec(dllexport) or, alternatively, use a .DEF file to expose a function to be able to call a DLL. (Because of name mangling in C++ for the __stdcall, I put aliases into the .DEF file so certain applications could re-use certain exported DLL functions.) Now, I am interested in being able to expose a single entry-point function from a .NET assembly, in unmanaged-fashion, but have it enter into .NET-style functions within the DLL. Is this possible, in a simple and straight-forward fashion?

What I have is a third-party program that I have extended through DLLs (plugins) that implement some complex mathematics. However, the third-party program has no means for me to visualize the calculations. I want to somehow take these pre-written math functions, compile them into a separate DLL (but using C++开发者_StackOverflow/CLI in .NET), but then add hooks to the functions so I can render what's going on under the hood in a .NET user control. I'm not sure how to blend the .NET stuff with the unmanaged stuff, or what to Google to accomplish this task.

Specific suggestions with regard to the managed/unmanaged bridge, or alternative methods to accomplish the rendering in the manner I have described would be helpful. Thank you.


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();
}


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;
  }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜