2013-07-22 25 views
-1

這裏是一段代碼:代表和本機方法

private static bool CreateDelegates() 
{ 
    IntPtr ptr; 

    //--- SoundTouch: createInstance 

    ptr = Kernel32Methods.GetProcAddress (libHandle, "[email protected]"); 

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

    //--- SoundTouch: destroyInstance 

    ptr = Kernel32Methods.GetProcAddress (libHandle, "[email protected]"); 

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

而且有更多的assigments像上面在此方法。我想創建像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(); 

幫助:)

回答

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到委託,所以你首先必須將GetDelegateForFunctionPointer的結果投到object之前將它鑄造成T

用法:

createInstance = CreateDelegate<st_createInstance>("[email protected]"); 
destroyInstance = CreateDelegate<st_destroyInstance>("[email protected]"); 
+0

錯誤:無法CONVER委派到T. – zgnilec

+0

@zgnilec:請參閱更新的代碼和解釋。 –

+0

它不能編譯「返回(T)元帥......」的位置。 – zgnilec