4

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

thoxey
  • 322
  • 3
  • 12

1 Answers1

7

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.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • Thanks, I misinterpreted the message to be referring to a "generic type definition" and not a "generic type" definition. Like what is outlined here: https://stackoverflow.com/questions/2564745/what-is-the-difference-between-a-generic-type-and-a-generic-type-definition – thoxey Feb 18 '21 at 12:49
  • Cheers! Glad I could help resolve this one! Don't forget to accept if it works for you! – Athanasios Kataras Feb 18 '21 at 12:51