2013-07-22 4 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 делегат Т. – zgnilec

+0

@zgnilec: Пожалуйста, смотрите обновленный код и объяснение. –

+0

Невозможно скомпилировать, где находится «return (T) Marshal ...». – zgnilec

Смежные вопросы