使用 GetFunctionPointerForDelegate 时出现异常:“指定的类型不能是泛型类型定义。”

tho*_*xey 4 .net c#

尝试使用GetFunctionPointerForDelegate通过互操作传递函数指针(C# -> C++)。但是,我得到了例外:The specified Type must not be a generic type definition.

据我所知,我没有传递泛型类型定义,在检查委托的类型时,我看到了以下内容: 在此输入图像描述

我写了一个最小的例子并观察到了相同的行为,对于我所缺少的任何建议,我将不胜感激。

using System;
using System.Runtime.InteropServices;
                    
public class MyTestClass
{
        public void Foo()
        {
            Delegate del = new Func<int, int>(Bar);
            IntPtr funcPtr = Marshal.GetFunctionPointerForDelegate(del);
        }

        public int Bar(int a)
        {
            return 0;
        }
}

public class Program
{
    public static void Main()
    {
        var mtc = new MyTestClass();
        mtc.Foo();
    }
}
Run Code Online (Sandbox Code Playgroud)

可以在 dotnet fiddle 上观察到该问题:https ://dotnetfiddle.net/8Aol9j

Ath*_*ras 7

阅读错误并尝试像这样的网络小提琴

        delegate int BarFunc(int a);
        public void Foo()
        {
            BarFunc del = Bar;
            IntPtr funcPtr = Marshal.GetFunctionPointerForDelegate(del);
        }

        public int Bar(int a)
        {
            return 0;
        }
Run Code Online (Sandbox Code Playgroud)

new Func<int, int>声明泛型类型。为了避免这种情况,请声明委托类型并按照示例代码和小提琴中的指示进行分配。