-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为委托,因此您首先必须将结果转换为GetDelegateForFunctionPointerto ,object然后再将其转换为T.

用法:

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