我的 C 声明如下:
int myData(uint myHandle, tchar *dataName, long *Time, uint *maxData, DATASTRUCT **data);
typedef struct {
byte Rel;
__int64 Time;
char Validated;
unsigned char Data[1];
} DATASTRUCT ;
我的 C# 声明如下:
[DllImport("myData.dll", EntryPoint = "myData")]
public static extern int myData(uint myHandle, [MarshalAs(UnmanagedType.LPTStr)] string dataName, out long Time, out uint maxData, ref DATASTRUCT[] data);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct DATASTRUCT
{
public sbyte Rel;
public long Time;
public byte Validated;
public double Data;
}
然后我按如下方式调用托管函数:
string dataToShow = "description";
long Time;
uint maxData; // How many structs will be returned, i.e. how much data is available
uint myHandle = 1;
DATASTRUCT[] dataInformation = new DATASTRUCT[3]; // doesn't matter what I specify as the array size?
myData(myHandle, dataToShow, out Time, out maxData, ref dataInformation);
执行后,即使有 3 个结构要返回,上述函数也将成功返回只有一个结构。为什么会这样?
附加信息; 我尝试通过以下方式将指针传递给结构数组的指针:
- ref DATASTRUCT[] data; // Works but only returns one struct
- [Out, MarshalAs(UnmanagedType.LPArray)] DATASTRUCT[] data; // returns the number of defined structs with garbage
据我了解,我可能需要使用 进行一些手动编组IntPtr
,但是我不知道如何实现这一点,所以任何建议都将不胜感激。