如何使用结构指针导入非托管 dll

本文关键字:dll 导入 何使用 结构 指针 | 更新日期: 2023-09-27 18:32:42

>我可以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();
}

如何使用结构指针导入非托管 dll

您可能需要使用 Marshal.GetDelegateForFunctionPointer 函数

这将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();