我正在编写一个 C# 应用程序,它使用互操作服务来访问 native C++ DLL 中的函数。我已经使用了大约 10 个正在运行的不同功能。
现在我不确定如何处理将回调作为参数传递,以便 DLL 可以调用我的代码。
这是DLL的函数原型(prototype):
typedef void (WINAPI * lpfnFunc)(const char *arg1, const char *arg2)
以及允许我传递上述类型的函数:
int WINAPI SetFunc(lpfnFunc f)
这是我的委托(delegate)和函数定义的 C# 代码:
public delegate void Func(string arg1, string arg2);
public static void MyFunc(string arg1, string arg2)
这是我的 SetFunc Interop 函数的 C# 代码:
[DllImport("lib.dll", CharSet = CharSet.Ansi)]
public static extern int SetFunc(Func lpfn);
最后是我调用 SetFunc 函数并向其传递回调的代码:
SetFunc(new Func(MyFunc));
不幸的是,我的函数没有在应该调用的时候被调用。 SetFunc 函数的返回值返回成功的错误代码,因此它要么没有调用我的函数,要么因为我的代码错误而无法工作。
最佳答案
这对我有用:
Calc.h(Calc.dll,C++):
extern "C" __declspec(dllexport) double Calc(double x, double y, double __stdcall p(double, double));
Calc.cpp(Calc.dll,C++):
#include "calc.h"
__declspec(dllimport) double Calc(double x, double y, double __stdcall p(double, double))
{
double s = p(x*x, y*y);
return x * y + s;
}
Program.cs(示例.exe,C#):
class Program
{
delegate double MyCallback(double x, double y);
[DllImport("Calc.dll", CallingConvention = CallingConvention.Cdecl)]
static extern double Calc(double x, double y, [MarshalAs(UnmanagedType.FunctionPtr)]MyCallback func);
static void Main(string[] args)
{
double z = Calc(1, 2, (x, y) => 45);
}
}
关于c# - 通过 Interop/pinvoke 传递 C# 回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9056048/