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:

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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With