【问题标题】:How to pass function pointer from C# to a C++ Dll?如何将函数指针从 C# 传递给 C++ Dll?
【发布时间】: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”函数?

【问题讨论】:

标签: c# c++ dll delegates pinvoke


【解决方案1】:

您的委托使用cdecl 调用约定。因此,在 C# 中,您可以像这样声明委托:

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

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

这样实现:

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

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

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

在此处的简单示例中,C++ 代码不使用TestDelegate 之外的非托管函数指针,但在更复杂的示例中,您可以这样做,在这种情况下,您必须保持非托管函数指针处于活动状态.

你导入的函数是这样声明的:

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

你可以这样称呼它:

double retval = TestDelegate(delegateInstance);

【讨论】:

    【解决方案2】:

    在 C++ 方面,我会明确指定回调的 调用约定,例如__stdcall(你的代码中没有这样做,我认为默认是__cdecl):

    // Include the calling convention (__stdcall) for the Callback
    typedef double (__stdcall * Callback)(double);
    
    // Just use "Callback" here, instead of repeating 
    // the above function prototype
    extern "C" __declspec(dllexport) __stdcall double TestDelegate(Callback func)
    {
        return func(25.0);
    }
    
    // BTW: Can export also using .DEF file to avoid __stdcall name mangling
    

    在 C# 方面,您可以尝试以下方法:

    public delegate double CallbackDelegate(double x);
    
    // PInvoke declaration for the native DLL exported function
    [DllImport("YourDLL.dll", CallingConvention = CallingConvention.StdCall)]
    public static extern double TestDelegate(CallbackDelegate func);
    
    private double MyFunctionCallback(double x)
    {
        // ... Implement your C# callback code ...
    }
    
    CallbackDelegate managedDelegate = new CallbackDelegate(MyFunctionCallback);
    
    // Call into the native DLL, passing the managed callback
    TestDelegate(managedDelegate);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 2011-04-17
      • 1970-01-01
      相关资源
      最近更新 更多