如何编组一个可变大小的结构数组? C#和C ++互操作帮助
我有以下C ++结构
struct InnerStruct { int A; int B; }; struct OuterStruct { int numberStructs; InnerStruct* innerStructs; };
还有一个C ++函数
OuterStruct getStructs();
我如何将其编组为C#? C#定义的位置
struct OuterStruct { InnerStruct[] innerStructs; };
您必须手动执行此操作,因为无法告诉P / Invoke层要从C ++返回值编组多少数据。
struct OuterStruct { int numberStructs; IntPtr innerStructs; }; OuterStruct s = getStructs(); // using DllImport var structSize = Marshal.SizeOf(typeof(InnerStruct)); var innerStructs = new List(); 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
的内存, innerStructs
必须在C ++代码中使用标准分配器CoTaskMemAlloc
- 然后可以调用Marshal.CoTaskMemFree
来释放innerStructs
。