簡體   English   中英

如何編組一個可變大小的結構數組? C#和C ++互操作幫助

[英]How to marshal a variable sized array of structs? C# and C++ interop help

我有以下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<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的內存, innerStructs必須在C ++代碼中使用標准分配器CoTaskMemAlloc - 然后可以調用Marshal.CoTaskMemFree來釋放innerStructs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM