110,578
社区成员
发帖
与我相关
我的任务
分享
C/C++中的定义如下:
/* 结构体定义*/
typedef struct _tag_RECORD
{
struct _tag_RECORD *next;
unsigned short *pName;
}RECORD_T, *P_RECORD_T;
/* 函数声明 */
int GetRecords(P_RECORD_T ppRecord[]);
在C#中需要调用GetRecords来获取相应的记录,pName内存应该是在dll中申请的.
我在C#中定义结构体如下:
public struct RecordType
{
public IntPtr next;
[MarshalAs(UnmanagedType.LPWStr)]
public string pName;
}
但是接下来却不知道怎么写了.
请问,如何在C#中调用GetRecords获取到记录的名字呢?谢谢.
/* 声明 */
[DllImport("***.dll")]
public static extern int GetRecords(IntPtr[] ppRecord);
int cnt = 1; //根据查询情况赋值,这里只查一个
int result = -1;
IntPtr[] record = new IntPtr[cnt]; //申请内存空间
record[0] = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(RECORD_T)) * cnt); //这样是okay的?我尝试了是没有问题的,但不保证
result = GetRecords(record);
if(0x00 != result)
{
//do something here
return;
}
else
{
RECORD_T tagInfo;
for (int i = 0; i < cnt; i++)
{
tagInfo = (RECORD_T)Marshal.PtrToStructure((IntPtr)((UInt32)record[i]),
typeof(RECORD_T));
//这里就成功获取到了信息了
}
}
... //more operation here
Marshal.FreeHGlobal(record[0]); //别忘了释放内存,但是我也不确定是否已经全部释放
[DllImport("**.dll")]//你要导入的库函数
public static extern int GetRecords(ref RecordType ppRecord )