-1

コードの一部を次に示します。

private static bool CreateDelegates ()
{
     IntPtr ptr;

     //--- SoundTouch: createInstance

     ptr = Kernel32Methods.GetProcAddress (libHandle, "_soundtouch_createInstance@0");

     if (ptr != IntPtr.Zero)
     {
         createInstance = (st_createInstance) Marshal.GetDelegateForFunctionPointer
                          (ptr, typeof (st_createInstance));
     }

     //--- SoundTouch: destroyInstance

     ptr = Kernel32Methods.GetProcAddress (libHandle, "_soundtouch_destroyInstance@4");

     if (ptr != IntPtr.Zero)
     {
         destroyInstance = (st_destroyInstance) Marshal.GetDelegateForFunctionPointer
                           (ptr, typeof (st_destroyInstance));
     }
}

そして、このメソッドには上記のような割り当てが他にもたくさんあります。コード量を減らすために AssignProc (...) のようなメソッドを作成したい。

void AssignProc (string procName, Delegate d, Type??? )
{
    IntPtr ptr;

    ptr = Kernel32Methods.GetProcAddress (libHandle, procName);

    if (ptr != IntPtr.Zero)
    {
        d = (Type???) Marshal.GetDelegateForFunctionPointer
                          (ptr, typeof (???));
    }
}

どこ:

 private static st_createInstance        createInstance;

 [UnmanagedFunctionPointer (CallingConvention.StdCall)]
 private delegate IntPtr st_createInstance ();

ヘルプ?:)

4

1 に答える 1

1

ジェネリックメソッドが必要だと思います:

T CreateDelegate<T>(string procName) where T : class
{
    IntPtr ptr;

    ptr = Kernel32Methods.GetProcAddress (libHandle, procName);

    if (ptr != IntPtr.Zero)
    {
        return (T)(object)Marshal.GetDelegateForFunctionPointer(ptr, typeof (T));
    }

    return null;
}

T残念ながら、デリゲートに制約することはできないため、最初に to の結果をキャストしてGetDelegateForFunctionPointerからobjectにキャストする必要がありTます。

使用法:

createInstance = CreateDelegate<st_createInstance>("_soundtouch_createInstance@0");
destroyInstance = CreateDelegate<st_destroyInstance>("_soundtouch_destroyInstance@4");
于 2013-07-22T13:13:09.500 に答える