我正在使用C ++编写一个非托管的dll。我可以从C#应用程序中轻松调用某些函数。但是一个功能让我受苦:)
问题出在log参数中。它应该反映为Data_Struct
类型的数组:
typedef struct
{
unsigned int id;
unsigned short year;
unsigned char month;
unsigned char day;
unsigned char hour;
unsigned char min;
unsigned char sec;
unsigned char status;
}Data_Struct;
int Read_Stored_Data(HUNIT pUnitHandle, int option, int updateFlag,
int maxEntries, unsigned char *log)
public struct Data_Struct
{
public uint id;
public ushort year;
public byte month;
public byte day;
public byte hour;
public byte min;
public byte sec;
public byte status;
}
[DllImport("SData.dll", EntryPoint = "Read_Stored_Data")]
public static extern int Read_Stored_Data(int pUnitHandle, int option,
int updateFlag, int maxEntries, ref Data_Struct[] log);
请假设我传递的pUnitHandle
,option
,updateFlag
,maxEntries
值正确。问题是最后一个参数(log
):
Data_Struct[] logs = new Data_Struct[1000];
res = Read_Stored_Data(handle, 1, 0, 1000, ref logs); // This should work but it
// causes the application
// to terminate!
有什么想法吗?
答案 0 :(得分:1)
尝试使用PInvoke属性。
具体来说,将布局应用于结构:
[StructLayout(LayoutKind.Sequential)]
public struct Data_Struct
{
public uint id;
public ushort year;
public byte month;
public byte day;
public byte hour;
public byte min;
public byte sec;
public byte status;
}
并对参数应用编组属性,同时删除ref
:
[DllImport("SData.dll", EntryPoint = "Read_Stored_Data")]
public static extern int Read_Stored_Data(int pUnitHandle, int option,
int updateFlag, int maxEntries, [MarshalAs(UnmanagedType.LPArray), Out()] Data_Struct[] log);
看看是否有帮助,相应调整。