PInvoke结构指针以获取数据
本文关键字:获取 数据 指针 结构 PInvoke | 更新日期: 2023-09-27 18:22:23
C代码:
// Device description structure
struct DeviceInfo
{
unsigned short deviceID;
unsigned short productID;
unsigned short versionNumber;
wchar_t* deviceName;
};
void __cdecl GetAttachedDevices(
int* count,
DeviceInfo* deviceInfoList
);
和PInvoke C#代码以使用此C DLL:
public struct DeviceInfo
{
public ushort deviceID;
public ushort productID;
public ushort versionNumber;
public IntPtr deviceName;
};
[DllImport("Native.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern void GetAttachedDevices(ref int count, ref DeviceInfo deviceInfoList);
当我使用这个C#代码时:
int count = 0;
DeviceInfo dev = new DeviceInfo();
GetAttachedDevices(ref count, ref dev);
我在dev中只得到一个设备信息(当count有两个设备时)。
我应该如何获取所有设备数据?
您需要分配并传递一个数组。像这样声明函数:
[DllImport("Native.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern void GetAttachedDevices(
ref int count,
[In, Out] DeviceInfo[] deviceInfoList
);
这样称呼它:
int count = 16; // not sure how you are expected to come up with this value
DeviceInfo[] dev = new DeviceInfo[count];
GetAttachedDevices(ref count, dev);
如何分配阵列?也许函数允许您为数组传递一个空指针,以获得所需的大小。在这种情况下,您有:
int count = 0;
GetAttachedDevices(ref count, null);
DeviceInfo[] dev = new DeviceInfo[count];
GetAttachedDevices(ref count, dev);
您将能够从C代码或其文档中计算出这些细节。
GetAttachedDevices可能需要一个数组,因此您应该修改第二个参数。
问题是:这个数组是由GetAttachedDevices分配的(然后谁应该销毁它?),还是希望你提供这个数组?
如果是后者,它如何处理您提供的数组不够大的情况?它是否将前N个设备复制到阵列中,并返回所需的总计数(大于阵列长度),期望您用更大的阵列重新调用GetAttachedDevices?