简体   繁体   中英

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 then 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM