【问题标题】:How to import the unmanaged dll with struct pointer?如何使用结构指针导入非托管 dll?
【发布时间】:2013-09-29 02:22:18
【问题描述】:

我可以DllImport常用函数,但是无法导入这种类型,下面是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();
}

【问题讨论】:

  • 我可以导入一些没有指针的函数,我想我应该用c#写一个struct,但我不知道如何处理指针
  • @igelineau ,我仍然无法正常工作。请您帮忙。
  • 这到底是怎么失败的?您是否尝试过使用 IntPtr 作为方法参数而不是 ref?
  • 您的struct 需要包含某种形式的函数指针,而不是方法。具有适当封送注释的委托可能会起作用。
  • @CodesInChaos 谢谢,我已经更新了内容,我已经测试了委托方法,但我找不到调用它的方法。可以举个例子吗?

标签: c# dllimport unmanaged


【解决方案1】:

您可能需要使用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();

【讨论】:

  • @lbasa 谢谢,我在 .Net CF 上工作,没有 GetDelegateForFunctionPointer。
  • 哦,那可能很棘手,我将编辑另一种方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-30
  • 1970-01-01
  • 2011-07-03
  • 2011-11-11
  • 2010-10-14
  • 2013-01-05
相关资源
最近更新 更多