在C中定义的函数++ DLL是:如何将函数指针从C#传递给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;
}
}
它不error.But被编译当它运行时,VS2012显示错误“访问违规例外”。
我已经搜索并尝试了很多方法,例如传递委托而不是IntPtr,但所有这些方法都失败了。
那么,在包含函数指针的dll中使用API函数的正确方法是什么?或者如何实现“My_Real_purpose”函数?
的可能的复制[妙传C++函数指针由C#调用 - 函数的参数包括宽字符串(LPCWSTR)](http://stackoverflow.com/questions/6282264/pass-a-function-pointer-from-c-to-be-called-by-c-sharp-函数参数) –
我删除了COM标签,因为这个问题与COM无关; PInvoke标签更合适。 –
委托声明是错误的,但这不足以解释AVE。确保您知道如何调试C++代码,以便您可以诊断此崩溃。显示你得到的堆栈跟踪。 –