Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception using GetFunctionPointerForDelegate: "The specified Type must not be a generic type definition. "

Tags:

c#

.net

Trying to use GetFunctionPointerForDelegate to pass a function pointer over interop, (C# -> C++). However, I am getting the exception: The specified Type must not be a generic type definition.

As far as I can tell I am not passing in a generic type definition, when inspecting the type of the delegate I saw the following: enter image description here

I wrote a minimum example and observed the same behaviour, would appreciate any advice as to what I'm missing.

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();
    }
}

The issue can be observed on dotnet fiddle: https://dotnetfiddle.net/8Aol9j

like image 763
thoxey Avatar asked Oct 29 '25 08:10

thoxey


1 Answers

Read the error and try like this 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;
        }

The new Func<int, int> declaration IS a generic type. To avoid this, declare a delegate type and assign as indicated in the sample code and the fiddle.

like image 62
Athanasios Kataras Avatar answered Oct 31 '25 00:10

Athanasios Kataras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!