C++ dll 中定义的函数是:
static double (*Func1)(double);
EXTERN_C __declspec(dllexport) __stdcall double TestDelegate(double (*fun)(double))
{
Func1 = fun;
return Func1(25.0);
}
void My_Real_purpose()
{
SomeClass a;
a.SetFunction(Func1);//Define behaviour of a by C# in runtime
a.DoSomething();//Even I want it runs in another thread!
}
我尝试使用C#调用它,代码如下:
class A
{
[DllImport("DllName.dll")]
public extern static double TestDelegate(IntPtr f);
public delegate double MyFuncDelegate(double x);
public static double MyFunc(double x)
{
return Math.Sqrt(x);
}
static MyFuncDelegate ff;
static GCHandle gch;
public static double Invoke()
{
ff = new MyFuncDelegate(MyFunc);
gch = GCHandle.Alloc(ff);
double c = TestDelegate(Marshal.GetFunctionPointerForDelegate(ff));//Error occurs this line
gch.Free();
return c;
}
}
编译没有错误,但运行时VS2012显示“访问冲突异常”的错误。
我已经搜索并尝试了很多方法,比如传递委托而不是IntPtr,但它们都失败了。
那么,在包含函数指针的dll中使用API函数的正确方法是什么?或者如何实现“My_Real_purpose”函数?