如何从本机 C(++) DLL 调用 .NET (C#) 代码?
我有一个 C# app.exe 和一个 C# my.dll。 my.dll .NET 项目链接到本机 C++ DLL (mynat.dll)(外部 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 导出“外部 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与普遍看法相反,这是可能的。
请参阅此处。
Contrary to popular belief, this is possible.
See here.
虽然 SLaks 提供的链接指向 Unmanaged Exportsutility 的链接可能有效,也可能无效,我们在这里使用了类似的工具(来自不同的来源),并且由于签名可执行文件的问题而放弃了这种方法。
我们得出以下结论,并将在将来这样做:
使 .NET 回调可用于纯本机模块的正确方法是编写一个 C++/CLR 项目,该项目对 .NET 程序集进行向上调用并导出本机接口。
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.