如何编组一个可变大小的结构数组? C#和C ++互操作帮助

时间:2009-07-28 22:53:53

标签: c# .net interop pinvoke marshalling

我有以下C ++结构

struct InnerStruct
{
   int A;
   int B;
};

struct OuterStruct
{
   int numberStructs;
   InnerStruct* innerStructs;
};

和C ++函数

OuterStruct getStructs();

我如何将其编组为C#? C#定义在哪里

struct OuterStruct {
   InnerStruct[] innerStructs;
};

1 个答案:

答案 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