ネイティブdllのP/Invokeラッパーを作成しているときに、次のようなコードがたくさんあることに気付きました。
// 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)
{
}
じゃあ後で、
// 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));
だから私は上記のように見えるかなり多くのコードになってしまいます。ジェネリック関数を使用したリファクタリングは、次のように便利だと思いました。
static void foo<T>(ref IntPtr ptr, T f) where T: System.Delegate, new()
{
ptr = Marshal.GetFunctionPointerForDelegate(new T(f));
}
それで私は次のように書くことができます:
foo<d1>(a,f1);
foo<d2>(b,f2);
等々。コンパイルされません!関数宣言にいくつかの型制約を追加しようとしましたが、機能させることができません。この場合、リファクタリングはほとんど重要ではないため、それほど重要ではありませんが、このようなことをどのように行うかを知りたいだけです。