委托和本机方法

本文关键字:方法 本机 | 更新日期: 2023-09-27 18:24:18

这里有一段代码:

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 ();

帮助?:)

委托和本机方法

我想你想要一个通用方法:

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约束为委托,因此必须先将GetDelegateForFunctionPointer的结果强制转换为object,然后再将其强制转换为T

用法:

createInstance = CreateDelegate<st_createInstance>("_soundtouch_createInstance@0");
destroyInstance = CreateDelegate<st_destroyInstance>("_soundtouch_destroyInstance@4");