开发者

How to call .NET (C#) code from a native C(++) DLL?

I have a C# app.exe and one C# my.dll. The my.dll .NET project links to a native C++ DLL (mynat.dll) (extern C DLL interface) and calling from C# into the C++ DLL works without problems. ( By using the [DllImport("mynat.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] attribute. )

What I need to add now is for the C# dll to provide some callback functions that the C++ code can call into. Ideally the mynat.dll C++ code would use LoadLibrary("my.dll") to load the C# dll and the开发者_运维问答n use GetProcAddress to resolve a callback function it can then call. (Note that at the point the C++ code calls LoadLibrary the my.dll C# dll is already loaded into the process - this call would just be to get a handle to the dll.)

However, I don't know what the correct way is to export an "extern C DLL interface" from a .NET DLL

What do I need to do to achieve this?


Contrary to popular belief, this is possible.
See here.


While the link provided by SLaks to the Unmanaged Exportsutility might or might not work, we used a similar tool (from a different source) here and due to problems with signed executables have abandoned this approach.

We have concluded the following and will do this in the future:

The correct way to make .NET callbacks available to pure native modules is to write a C++/CLR project that does the upcalls to to .NET assembly and exports a native interface.

[ .NET ] -> ----------- -> [ C(++) ]  ... via DllImport Attribute

[ .NET ] <- [ C++/CLR ] <- [ C(++) ]  ... "default" .NET interface + "default" native interface
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜