2013-07-22 3 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 (...)과 같은 메서드를 만들고 싶습니다. ?

private static st_createInstance  createInstance; 

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

도움말 : 내 생각

답변

1

당신이 일반적인 방법 원하는 :

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

    ptr = Kernel32Methods.GetProcAddress (libHandle, procName); 

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

불행하게도

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

오류 : T.에 – zgnilec

+0

@zgnilec을 위임을 Conver 유럽 수 없습니다 : 업데이트 된 코드와 설명을 참조하십시오. –

+0

"return (T) Marshal ..."이 (가) 컴파일 될 수 없습니다. – zgnilec