How to convert cli :: array to native array from native code?

I am writing my own 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 got to calling a managed function from within my own code, but I'm not sure how to safely copy a managed array to an unmanaged one.

 gcroot<cli::array<System::Byte>^> managedArray = _managedObject->Function(); 
+4
source share
2 answers

There are two common approaches:

  • Marshal using your own code, which requires the 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 marshaling with managed code that requires the 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; } 

As a rule, I would prefer the latter approach, since the former can hamper the efficiency of the GC if the array is large.

+7
source

Take a look at pin_ptr , it allows you to pass the address of a managed class to an unmanaged function.

0
source

All Articles