我如何将一个CLI ::阵列从本地code本地阵列? [英] How do I convert a cli::array to a native array from native code?
问题描述
我写周围写在C ++ \ CLI的托管组件的本机包装。
我在管理code以下功能:
阵列和LT;字节> ^类::函数();
我想从一个本地C暴露该功能++类具有以下签名:
shared_array< unsigned char型>类::函数();
我已经得到了尽可能调用从本地code中的管理功能,但我不知道如何安全地复制管理的阵列到非托管的。
gcroot< CLI ::数组<系统::字节> ^> managedArray = _managedObject->功能();
有两种常用的方法:
-
执行与本机code,这需要使用的
pin_ptr<>
:的boost :: shared_array< unsigned char型>转换(阵列< unsigned char型> ^ ARR) { 提高:: shared_array< unsigned char型> DEST(新的无符号的char [arr->长度]); pin_ptr< unsigned char型>钉扎=安培;常用3 [0]; 无符号字符* SRC =固定; 性病::复制(SRC,SRC + arr->长度,dest.get()); 返回DEST; }
-
执行与管理code,这就要求使用的元帅类:
的boost :: shared_array< unsigned char型>转换(阵列< unsigned char型> ^ ARR) { 使用系统:运行时:: InteropServices ::元帅; 提高:: shared_array< unsigned char型> DEST(新的无符号的char [arr->长度]); 元帅::复制(ARR,0,IntPtr的(dest.get()),arr->长度); 返回DEST; }
一般来说,我会preFER后一种方式,因为前者会阻碍GC的有效性,如果数组是很大的。
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();
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();
There are two usual approaches:
Perform the marshaling with native code, which requires use of
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; }
Perform the marshaling with managed code, which requires use of the Marshal class:
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; }
Generally I would prefer the latter approach, as the former can hinder the GC's effectiveness if the array is large.
这篇关于我如何将一个CLI ::阵列从本地code本地阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!