如何从本机C(++)DLL调用.NET(C#)代码? [英] How to call .NET (C#) code from a native C(++) DLL?
问题描述
我有一个C#app.exe和一个C#my.dll。 my.dll .NET项目链接到本地C ++ DLL(mynat.dll)(extern C DLL接口),并从C#调用到C ++ DLL工程没有问题。 (使用 [DllImport(mynat.dll,CharSet = CharSet.Unicode,CallingConvention = CallingConvention.Cdecl)]
属性。)
我现在需要添加的是C#dll提供一些C ++代码可以调用的回调函数。理想情况下,mynat.dll C ++代码将使用LoadLibrary(my.dll)加载C#dll,然后使用GetProcAddress来解析它可以调用的回调函数。 (注意,在C ++代码调用LoadLibrary的时候,my.dll C#dll已经加载到进程中 - 这个调用只是获取dll的句柄。)
但是,我不知道正确的方法是从.NET DLL导出extern C DLL接口
我需要做什么 首页/上传/ unmanagedexportsrel =nofollow>链接提供的SLaks 到非管理Exportsutility可能或可能不工作,我们在这里使用类似的工具(从不同的来源)和由于签名的可执行文件的问题有放弃了这种方法。
我们总结了以下内容,并将在未来这样做:
使.NET回调可用于纯本地模块是编写一个C ++ / CLR项目,将上传到.NET汇编并导出一个本地接口。
[.NET] - > ----------- - > [C(++)] ...通过DllImport属性
[.NET] < - [C ++ / CLR] < - [C(++)] ... NET接口+默认本地接口
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?
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
这篇关于如何从本机C(++)DLL调用.NET(C#)代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!