如何将cli ::数组从本地代码转换为本机数组? [英] How do I convert a cli::array to a native array from native code?
问题描述
我在用C ++ \CLI编写的托管组件周围编写一个本地包装器。
I'm writing a native wrapper around a managed component written in C++\CLI.
我在托管代码中有以下函数:
I have the following function in managed code:
array<Byte>^ Class::Function();
我想使用以下签名从本地C ++类公开此函数:
I want to expose this function from a native C++ class with the following signature:
shared_array<unsigned char> Class::Function();
我已经从本地代码调用管理函数,但我不确定如何安全地将受管阵列复制到非托管阵列中。
I've gotten as far as calling the managed function from native code, but I'm not sure how to safely copy the managed array into an unmanaged one.
gcroot<cli::array<System::Byte>^> managedArray = _managedObject->Function();
推荐答案
有两种常用方法:
-
使用本机代码执行封送处理,这需要使用
pin_ptr<>
:
boost::shared_array<unsigned char> convert(array<unsigned char>^ arr)
{
boost::shared_array<unsigned char> dest(new unsigned char[arr->Length]);
pin_ptr<unsigned char> pinned = &arr[0];
unsigned char* src = pinned;
std::copy(src, src + arr->Length, dest.get());
return dest;
}
使用托管代码执行封送处理, a href =http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.aspx =nofollow> Marshal 类:
boost::shared_array<unsigned char> convert(array<unsigned char>^ arr)
{
using System::Runtime::InteropServices::Marshal;
boost::shared_array<unsigned char> dest(new unsigned char[arr->Length]);
Marshal::Copy(arr, 0, IntPtr(dest.get()), arr->Length);
return dest;
}
后者的方法,因为前者可以阻碍GC的有效性,如果数组很大。
Generally I would prefer the latter approach, as the former can hinder the GC's effectiveness if the array is large.
这篇关于如何将cli ::数组从本地代码转换为本机数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!