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

发布于 2024-07-29 16:04:52 字数 348 浏览 4 评论 0原文

我有以下 C++ 结构体

struct InnerStruct
{
   int A;
   int B;
};

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

和 C++ 函数,

OuterStruct getStructs();

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

struct OuterStruct {
   InnerStruct[] innerStructs;
};

I have the following C++ structs

struct InnerStruct
{
   int A;
   int B;
};

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

And a C++ function

OuterStruct getStructs();

How can I marshal this to C#? Where the C# definitions is

struct OuterStruct {
   InnerStruct[] innerStructs;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦断已成空 2024-08-05 16:04:52

您必须手动执行此操作,因为无法告诉 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

You'll have to do this manually, since there's no way to tell the P/Invoke layer how much data to marshal from your C++ return value.

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;
}

Note that if you want to free the memory for innerStructs from your C# code, you have to use the standard allocator CoTaskMemAlloc in your C++ code--then you can call Marshal.CoTaskMemFree to free innerStructs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文