C# 如何使用结构指针导入非托管dll?
我可以DllImport常用函数,但这类导入失败,下面是DLL头文件C# 如何使用结构指针导入非托管dll?,c#,dllimport,unmanaged,C#,Dllimport,Unmanaged,我可以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); 我
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
{
delegate void API_GetUID(IntPtr pData, int DataLen);
delegate void API_GetChipType();
}
您可能需要使用 这需要一个指向本机方法的
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();
我可以导入一些没有指针的函数,我想我应该用c#编写一个结构,但我不知道如何处理pointer@igelineau,我还是不能让它工作。你能帮忙吗?这到底是怎么失败的?您是否尝试过使用IntPtr作为方法参数而不是ref?您的
struct
需要包含某种形式的函数指针,而不是方法。可能具有正确封送批注的委托会起作用。@code谢谢,我已经更新了内容,我已经测试了委托方法,但我找不到调用它的方法。你能给我举个例子吗?@lbasa谢谢,我在.Net CF上工作,没有GetDelegateForFunctionPointer。哦,那可能会很棘手,我会用另一种方式编辑。
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();
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();