如何将函数指针从C#传递到C ++ Dll?

问题描述:

在C ++ dll中定义的函数是:

The function defined in C++ dll is:

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#中调用它:

And I tried to call it in C# like this:

    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会显示访问冲突异常"错误.

It is compiled without error.But when it runs,VS2012 display an error of "Access Violation Exception".

我已经搜索并尝试了很多方法,例如传递一个委托而不是一个IntPtr,但是所有方法都被证明失败了.

I have searched and tried a lot of ways,such as passing a delegate rather than a IntPtr,but all of them turned out to be failed.

那么,在包含函数指针的dll中使用API​​函数的正确方法是什么?或者如何实现"My_Real_purpose"函数?

So,what is the correct way to use an API function in a dll which contains function pointer?Or how to realize "My_Real_purpose" function?

您的委托使用 cdecl 调用约定.因此,在C#中,您将这样声明委托:

Your delegate uses the cdecl calling convention. In C# you would therefore declare the delegate like this:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate double CallbackDelegate(double x);

作为替代方案,您可以决定将C ++中的函数指针声明为 __ stdcall ,在这种情况下,您将删除 UnmanagedFunctionPointer 属性并依靠默认的调用约定正在 CallingConvention.StdCall .

As an alternative, you could decide to declare the function pointer in C++ as __stdcall, in which case you would remove the UnmanagedFunctionPointer attribute and rely on the default calling convention being CallingConvention.StdCall.

像这样实现它:

public static double MyFunc(double x)
{
    return Math.Sqrt(x);
}

为了使非托管函数指针保持活动状态(防止GC),您需要在变量中保存委托的实例.

In order to keep the unmanaged function pointer alive (guarding against GC), you need to hold an instance of the delegate in a variable.

private static CallbackDelegate delegateInstance;
....
delegateInstance = MyFunc;

在这里提供的简单示例中,C ++代码不会在 TestDelegate 之外使用非托管函数指针,但是在更复杂的示例中,您可以这样做,在这种情况下,您必须保持非托管函数指针仍然有效.

In the simple example that you have here, the C++ code does not use the unmanaged function pointer outside of TestDelegate, but in a more complex example you may do so, in which case you must keep the unmanaged function pointer alive.

导入的函数声明如下:

[DllImport("DllName.dll")]
public extern static double TestDelegate(CallbackDelegate f);

然后您可以这样称呼它:

You can then call it like this:

double retval = TestDelegate(delegateInstance);