如何从本机C(++)DLL调用.NET(C#)代码? [英] How to call .NET (C#) code from a native C(++) DLL?

查看:171
本文介绍了如何从本机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.Unicode,CallingConvention = CallingConvention.Cdecl)] 属性。)

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. )

我需要什么,现在补充的是为C#DLL提供一些回调函数的C ++代码可以调用。理想情况下,mynat.dll C ++代码将使用调用LoadLibrary(my.dll)来加载C#DLL,然后使用GetProcAddress的解决回调函数,然后它可以调用。 (请注意,在C ++代码调用LoadLibrary点的my.dll C#DLL已加载到进程 - 这一呼吁也只是得到一个句柄DLL。)

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.)

不过,我不知道正确的方法是从一个.NET的DLL导出一个外部C 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?

推荐答案

虽然的按SLaks提供非托管Exportsutility链接可能会或可能无法正常工作,我们使用了一个类似的工具(从不同的来源),这里因问题签名的可执行程序有。放弃了这种做法。

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.

的正确方法使.NET回调可用于纯本机模块是写一个C ++ / CLR项目,做了向上调用到.NET程序集和导出原生界面。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆