【问题标题】:Exception using GetFunctionPointerForDelegate: "The specified Type must not be a generic type definition. "使用 GetFunctionPointerForDelegate 的异常:“指定的类型不能是泛型类型定义。”
【发布时间】:2021-02-18 20:41:07
【问题描述】:

尝试使用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();
    }
}

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

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    阅读错误并尝试这样net fiddle

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

    new Func&lt;int, int&gt; 声明 一个泛型类型。为避免这种情况,请声明一个委托类型并按照示例代码和小提琴中的说明进行分配。

    【讨论】:

    • 谢谢,我将消息误解为指的是“泛型类型定义”而不是“泛型类型”定义。就像这里概述的那样:stackoverflow.com/questions/2564745/…
    • 干杯!很高兴我能帮助解决这个问题!如果它对您有用,请不要忘记接受!
    猜你喜欢
    • 2014-10-06
    • 2012-02-06
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2018-08-03
    相关资源
    最近更新 更多