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

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

Now I need to add so that C # dll provides some callback functions that C ++ code can call. Ideally, mynat.dll C ++ code will use LoadLibrary ("my.dll") to load the C # DLL, and then use GetProcAddress to solve the callback function that it can call. (Note: at the point where the C ++ code calls LoadLibrary, the dll dll my.dll is already loaded into the process - this call will only be to get the dll descriptor.)

However, I do not know how to correctly export the "extern C DLL interface" from the .NET DLL

What do I need to do to achieve this?

+4
source share
2 answers

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

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

The right way to make .NET callbacks available to pure native modules is to write a C ++ / CLR project that makes upcalls for .NET assembly and exports its own interface.

 [ .NET ] -> ----------- -> [ C(++) ] ... via DllImport Attribute [ .NET ] <- [ C++/CLR ] <- [ C(++) ] ... "default" .NET interface + "default" native interface 
0
source

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

+2
source

Source: https://habr.com/ru/post/1336158/


All Articles