泛型类委托上的函数指针

问题描述 投票:0回答:1

我需要获取 FunctionPointerForDelegate 来传递本机 P/Invoke,但该函数驻留在 myClass 类型的泛型类中

当我尝试创建指针时,出现错误

System.ArgumentException: 'The specified Type must not be a generic type. (Parameter 'delegate')'

有什么解决办法吗?

var c = new MyClass<int>();
c.DoWork();

public class MyClass<T> {

    private protected delegate int MyCompareCallback(int idxA, int idxB);

    private int SortCompareFunction(int idxA, int idxB) {
        return -1; // simplified implementation
    }

    public void DoWork() {
        MyCompareCallback SortCallback = new(SortCompareFunction);
        IntPtr callbackPtr = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(SortCallback);
        Console.WriteLine("Success"); // Fails on previous line with System.ArgumentException: 'The specified Type must not be a generic type. (Parameter 'delegate')'
    }

}

c# delegates
1个回答
0
投票

您需要考虑您的委托类型

MyCompareCallback
实际上是
MyClass<T>.MyCompareCallback
。这是一个通用类型。

当您阅读 Marshal.GetFunctionPointerForDelegate 的文档时,它特别指出,如果委托是泛型类型,则会抛出

System.ArgumentException

你真的有两个选择。

(1) 从

MyClass

中删除泛型类型参数
public class MyClass
{
    private protected delegate int MyCompareCallback(int idxA, int idxB);
    private int SortCompareFunction(int idxA, int idxB) => -1;
    public void DoWork()
    {
        MyCompareCallback SortCallback = new MyCompareCallback(SortCompareFunction);
        IntPtr callbackPtr = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(SortCallback);
        Console.WriteLine("Success");
    }
}

(2) 将代表移出

MyClass<T>

internal delegate int MyCompareCallback(int idxA, int idxB);
public class MyClass<T>
{
    private int SortCompareFunction(int idxA, int idxB) => -1;
    public void DoWork()
    {
        MyCompareCallback SortCallback = new MyCompareCallback(SortCompareFunction);
        IntPtr callbackPtr = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(SortCallback);
        Console.WriteLine("Success");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.