本文介绍了如何编组结构的可变大小的数组? C#和C ++互操作的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的C ++结构
结构InnerStruct
{
诠释A;
INT B:
};
结构OuterStruct
{
诠释numberStructs;
InnerStruct * innerStructs;
};
和C ++函数
OuterStruct getStructs();
我怎么能这样编组的C#?当C#定义为
结构OuterStruct {
InnerStruct [] innerStructs;
};
解决方案
您需要手动做到这一点,因为没有办法告诉的P / Invoke层有多少数据从C到元帅++返回值。
结构OuterStruct {
诠释numberStructs;
IntPtr的innerStructs;
};
OuterStruct S = getStructs(); //使用的DllImport
VAR structSize = Marshal.SizeOf(typeof运算(InnerStruct));
VAR innerStructs =新的名单,其中,InnerStruct>();
VAR PTR = s.innerStructs;
的for(int i = 0; I< s.numberStructs;我++)
{
innerStructs.Add((InnerStruct)Marshal.PtrToStructure(PTR,
typeof运算(InnerStruct));
PTR =(IntPtr的)((INT)PTR + structSize);
}
请注意,如果你想免费为 innerStructs
内存从C#code,你必须使用标准分配器 CoTaskMemAlloc来
在C ++ code - 那么你可以调用 Marshal.CoTaskMemFree
免费 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;
};
解决方案
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 = (IntPtr)((int)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
.
这篇关于如何编组结构的可变大小的数组? C#和C ++互操作的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!