【发布时间】:2017-08-30 19:35:41
【问题描述】:
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显示“Access Violation Exception”的错误。
我已经搜索并尝试了很多方法,例如传递委托而不是 IntPtr,但所有方法都失败了。
那么,在包含函数指针的dll中使用API函数的正确方法是什么?或者如何实现“My_Real_purpose”函数?
【问题讨论】:
-
我删除了COM标签,因为这个问题与COM无关; PInvoke 标签更合适。
-
委托声明是错误的,但这不足以解释 AVE。确保您知道如何调试 C++ 代码,以便诊断此崩溃。显示你得到的堆栈跟踪。
标签: c# c++ dll delegates pinvoke