我已经看到了一些如何从 C++ 非托管 dll 到 C++ 托管 CLR dll 执行此操作的示例。我当前有一个 C++ dll (NetPcapWrap),它引用 C dll (npcap.dll)。由于 npcap.dll 是用 C 编写的,因此我无法使用 CLR 进行编译,因此 NetPcapWrap 是非托管的。我的 .Net Forms 应用程序使用 pInvoke 引用 NetPcapWrap.dll 从 npcap.dll 获取信息。
npcap.dll 中有一个循环函数,它将数据写入 std::out 我需要做的事情是调用 .Net windows Forms 应用程序的委托。
我已经看到了一个潜在的解决方案https://www.codeproject.com/tips/695387/calling-csharp-net-methods-from-unmanagement-c-cplusp但这将需要另一个编译的dll已启用 CLR。
有没有办法将 pInvoke 从非托管 C++ dll“反向”到 .Net Winforms 应用程序?
抱歉,我没有任何代码可发布,因为我不知道如何编写药水。我可以分享我如何调用 C++ dll,但这不是我的问题。
谢谢
您需要 csharp 代码将委托发送到需要函数指针的 C 函数,然后将其存储在某个全局中。
并且 C# 还需要将此委托存储在静态变量中,以防止 GC 清理它。
using myfunctype = void (*)(void);
extern "C"
__declspec( dllexport )
myfunctype func1;
myfunctype func1 = nullptr;
extern "C"
__declspec( dllexport )
int SetFunction(void (*func_ptr)(void))
{
func1 = func_ptr;
return 5;
}
extern "C"
__declspec( dllexport )
int CallFunction()
{
func1();
return 5;
}
using System.Runtime.InteropServices;
namespace myspace;
public delegate void CFunc();
public class NativeLib
{
public static void CsharpFunc()
{
Console.WriteLine("hello world from Csharp!");
}
public static CFunc func_static = CsharpFunc;
[DllImport("Clib", CallingConvention = CallingConvention.Cdecl)]
public static extern int SetFunction(CFunc func);
[DllImport("Clib", CallingConvention = CallingConvention.Cdecl)]
public static extern int CallFunction();
}
然后你的主应用程序需要调用它们。
using myspace;
class Program
{
public static int Main(String[] args)
{
NativeLib.SetFunction(NativeLib.func_static);
NativeLib.CallFunction();
return 0;
}
}
作为奖励,这也适用于不存在托管 C++ dll 的 Linux/macos。