. Net – Convert System:: array to STD:: vector
•
Java
Does anyone know that cli / Net system:: array is a simple method to convert C STD:: vector, in addition to operating as an element?
I am writing a wrapper method (setlowerboundswrapper below) in cli / C, which takes a system:: array as a parameter and passes the equivalent STD:: vector to the native C method (set_lower_bounds) At present, I do the following:
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); }
Solution
Another way is to let the Net BCL replaces C standard library to complete the work:
#include <vector> void SetLowerBoundsWrapper(array<double>^ lb) { using System::IntPtr; using System::Runtime::InteropServices::Marshal; std::vector<double> lower(lb->Length); Marshal::Copy(lb,IntPtr(&lower[0]),lb->Length); _opt->set_lower_bounds(lower); }
Editor (in response to comments on Konrad's answers):
Both of the following are compiled for me using VC 2010 Sp1 and are completely 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); }
(the manual range is to allow pin_ptr to release the memory as soon as possible, so as not to hinder the GC.)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码