In writing P/Invoke wrapper for a native dll, I found myself with a lot of code looking like this:
// Declare delegate types matching some callbacks in the dll
delegate void d1(T1, T1);
delegate void d2(T1,T2,T3);
// Some functions
void f1(T1 a, T2 b)
{
..
}
void f2(T1 a, T2 b, T3 c)
{
}
Then later,
// Marshal some instantiated delegates into IntPtrs to pass to native dll
IntPtr a = Marshal.GetFunctionPointerForDelegate(new d1(f1));
IntPtr b = Marshal.GetFunctionPointerForDelegate(new d2(f2));
So I end up with quite a lot of code looking like the above. I thought some refactoring using a generic function might be nice, something like this:
static void foo<T>(ref IntPtr ptr, T f) where T: System.Delegate, new()
{
ptr = Marshal.GetFunctionPointerForDelegate(new T(f));
}
Which would allow me to then write:
foo<d1>(a,f1);
foo<d2>(b,f2);
and so on. It doesn’t compile! I tried to add some type constraints onto the function declaration, but can’t get it to work. It’s not that important to me in this instance, as the re-factoring is hardly very important, but I’m just curious to know how I’d do something like this?
Sadly, you cannot constraint a type to inherit from System.Delegate. This limitation has frustrated me many times. The only way around this for you is to constrain the delegate to be a reference type and then do a nasty-ish cast:
You are not able to do a
new T(f)because theT:new()constraint only allows a parameterless constructor. The good news is that this is unnecessary asTis already a delegate type. You would need to invoke it like: