How to convert System :: array to std :: vector?

Is there any simple way to convert CLI / .NET System::array to C ++ std::vector , in addition to doing this bitwise?

I am writing a wrapper method ( SetLowerBoundsWrapper, below ) in CLI / C ++ that takes System::array as an argument and passes the equivalent std::vector to its own C ++ method ( set_lower_bounds ). I am currently doing this as follows:

 using namespace System; void SetLowerBoundsWrapper(array<double>^ lb) { int n = lb->Length; std::vector<double> lower(n); //create a std::vector for(int i = 0; i<n ; i++) { lower[i] = lb[i]; //copy element-wise } _opt->set_lower_bounds(lower); } 
+6
source share
1 answer

Another approach that allows .NET BCL to do the job instead of the standard C ++ library:

 #include <vector> void SetLowerBoundsWrapper(array<double>^ lb) { using System::IntPtr; using System::Runtime::InteropServices::Marshal; std::vector<double> lower(lb->Length); Marshal::Copy(lb, 0, IntPtr(&lower[0]), lb->Length); _opt->set_lower_bounds(lower); } 

The following compiles for me with V C ++ 2010 SP1, and are exactly equivalent:

 #include <algorithm> #include <vector> void SetLowerBoundsWrapper(array<double>^ lb) { std::vector<double> lower(lb->Length); { pin_ptr<double> pin(&lb[0]); double *first(pin), *last(pin + lb->Length); std::copy(first, last, lower.begin()); } _opt->set_lower_bounds(lower); } void SetLowerBoundsWrapper2(array<double>^ lb) { std::vector<double> lower(lb->Length); { pin_ptr<double> pin(&lb[0]); std::copy( static_cast<double*>(pin), static_cast<double*>(pin + lb->Length), lower.begin() ); } _opt->set_lower_bounds(lower); } 

Artificial pin_ptr - allow pin_ptr to pin_ptr as much as possible so as not to interfere with pin_ptr .

+10
source

Source: https://habr.com/ru/post/893696/


All Articles