2013-09-24 38 views
2

我可以通過DllImport的常用功能,但未能導入這種類型,下面是DLL頭文件。如何使用結構指針導入非託管dll?

typedef struct 
{ 
    VOID (* API_GetUID)(CHAR *pData, DWORD DataLen); 

    DWORD (* API_GetChipType)(); 

} API_FUNCTION_STRUCT, *API_FUNCTION_STRUCT; 

extern VOID WINAPI GetAPIObject(API_FUNCTION_STRUCT *pApiFunc); 

我不能在C#中編寫正確的結構。

public struct test 
    { 
     IntPtr API_GetUID(IntPtr pData, int DataLen); 
     IntPtr  API_GetChipType(); 
    } 

[DllImport(@"GDevice.dll")] 
public static extern void GetAPIObject(ref test test_a); 

更新:

public struct test 
{ 
delegate void API_GetUID(IntPtr pData, int DataLen); 
delegate void API_GetChipType(); 
} 
+0

我可以導入沒有指針的一些功能,我覺得我應該寫在C#中的結構,但我不知道如何處理指針 –

+0

@igelineau,我仍然無法得到它的工作。你能幫忙嗎? –

+0

這究竟如何失敗?你有沒有嘗試使用IntPtr的方法參數,而不是ref? – Nanhydrin

回答

2

您可能需要使用Marshal.GetDelegateForFunctionPointer function

這需要一個IntPtr指向一個本地方法,讓您回一個代表,你可以調用。

public struct test 
{ 
    IntPtr API_GetUID; 
    IntPtr API_GetChipType; 
} 

[DllImport(@"GDevice.dll")] 
public static extern void GetAPIObject(ref test test_a); 

delegate void GetUID_Delegate(IntPtr pData, uint dataLen); 
delegate uint GetChipType_Delegate(); 

test a = new test(); 
GetAPIObject(ref a); 

GetUID_Delegate getUID = Marshal.GetDelegateForFunctionPointer<GetUID_Delegate>(a.API_GetUID); 
GetChipType_Delegate getChipType = Marshal.GetDelegateForFunctionPointer<GetChipType_Delegate>(a.API_GetChipType); 

uint chipType = getChipType(); 

編輯

或者使用UnmanagedFunctionPointerAttribute

public struct test 
{ 
    GetUID_Delegate API_GetUID; 
    GetChipType_Delegate API_GetChipType; 

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)] 
    delegate void GetUID_Delegate(IntPtr pData, uint dataLen); 
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)] 
    delegate uint GetChipType_Delegate(); 
} 

[DllImport(@"GDevice.dll")] 
public static extern void GetAPIObject(ref test test_a); 

test a = new test(); 
GetAPIObject(ref a); 

uint chipType = a.API_GetChipType(); 
+0

@lbasa謝謝,我在.NET CF上工作,沒有GetDelegateForFunctionPointer。 –

+0

哦,那可能會很棘手,我會編輯另一種方法。 – Ibasa

相關問題