我有以下C ++结构
struct InnerStruct
{
int A;
int B;
};
struct OuterStruct
{
int numberStructs;
InnerStruct* innerStructs;
};
和C ++函数
OuterStruct getStructs();
我如何将其编组为C#? C#定义在哪里
struct OuterStruct {
InnerStruct[] innerStructs;
};
答案 0 :(得分:22)
你必须手动执行此操作,因为没有办法告诉P / Invoke层要从C ++返回值编组多少数据。
struct OuterStruct {
int numberStructs;
IntPtr innerStructs;
};
OuterStruct s = getStructs(); // using DllImport
var structSize = Marshal.SizeOf(typeof(InnerStruct));
var innerStructs = new List<InnerStruct>();
var ptr = s.innerStructs;
for (int i = 0; i < s.numberStructs; i++)
{
innerStructs.Add((InnerStruct)Marshal.PtrToStructure(ptr,
typeof(InnerStruct));
ptr = ptr + structSize;
}
请注意,如果要从C#代码中释放innerStructs
的内存,则必须在C ++代码中使用标准分配器CoTaskMemAlloc
- 然后您可以调用Marshal.CoTaskMemFree
免费innerStructs
。