简体   繁体   English

保持从C ++编组到C#中的数组

[英]Holding onto an array marshalled into C# from C++

I am passing an array of integers from C++ to C#, using a parameter like this in my C# method: 我在C#方法中使用像这样的参数,将整数数组从C ++传递给C#:

[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] 
UInt32[] myStuff,

When this data arrives in the CLR, I think that "LPArray" indicates that I am working with the pointer from the C++-world directly? 当此数据到达CLR时,我认为“ LPArray”表示我正在直接使用C ++世界中的指针吗? So if I want to hold onto this array after the method call is over, should I make a copy of it? 因此,如果我想在方法调用结束后保留​​此数组,是否应该复制它?

You have to be careful that this is allocated using the same memory allocation mechanisms in both the managed and unmanaged worlds. 您必须注意,在托管和非托管环境中使用相同的内存分配机制进行分配。 And even if that's the case, it's just safer to make a copy and work with that. 即使是这样,制作副本并使用它也更安全。

Note: In your example, the pointer isn't passed by reference, and so the callee can only add to your previous array, not give you a new array. 注意:在您的示例中, 指针没有通过引用传递,因此被调用方只能添加到您以前的数组,而不能给您新的数组。 Is that really what you intended? 那真的是您想要的吗?

Calling from unmanaged code into managed code (C++ to C#), the array gets copied into a fully managed array. 从非托管代码调用到托管代码(从C ++到C#),该数组将被复制到完全托管的数组中。 This array will be freed when the garbage collector notices that nobody has any more references to it, not when the function exits. 当垃圾收集器注意到没有人对其有更多引用时,而不是在函数退出时,将释放此数组。

But the other direction is more dangerous: If you were going the other direction (C# to C++), it would either: pin the C# array so it won't move, or make a temporary copy of the array into unmanaged memory (which gets freed when the function returns). 但是另一个方向更危险:如果您正在朝另一个方向(从C#到C ++)执行,则可能是:固定C#数组以使其不会移动,或者将数组临时复制到不受管的内存中(函数返回时释放)。 In either case, it would not be safe to hold onto the array on the C++ side after the function call completes, you'd want to copy the contents to somewhere else. 无论哪种情况,在函数调用完成后,都不能安全地保留C ++端的数组,您需要将内容复制到其他地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM