问题描述
有谁知道有没有简单的方法来转换一个CLI /。NET系统::数组到C ++的std :: vector的,除了做逐元素?
我在写一个包装方法(SetLowerBoundsWrapper,下同)在CLI / C ++,它接受一个系统::数组作为参数,并通过等价的std ::矢量一个本地C ++方法(set_lower_bounds)。目前,我这样做如下:
使用命名空间系统;
无效SetLowerBoundsWrapper(阵列<双> ^磅)
{
INT N = LB->长度;
的std ::矢量<双>较低的(N); //创建一个std ::矢量
的for(int i = 0;我n种;我++)
{
较低的[I] =磅[I] //复制元素智能
}
_opt-> set_lower_bounds(低级);
}
另一种方法,让.NET基础类库做的工作,而不是C ++标准库:
的#include<载体>无效SetLowerBoundsWrapper(阵列<双> ^磅){ 使用系统:: IntPtr的; 使用系统:运行时:: InteropServices ::元帅; 的std ::矢量<双>低(LB->长度); 元帅:复制(磅,0,IntPtr的(安培低级[0]),LB->长度); _opt-> set_lower_bounds(低级);}
修改(针对在康拉德的回答评论):
以下都为我编译VC ++ 2010 SP1,并且是完全等价的:
的#include<算法>#包括<载体>无效SetLowerBoundsWrapper(阵列<双> ^磅){ 的std ::矢量<双>低(LB->长度); { pin_ptr<双>销(安培;磅[0]); 双*第一(PIN),*最后(销+ LB->长度); 性病::复制(第一,最后,lower.begin()); } _opt-> set_lower_bounds(低级);}无效SetLowerBoundsWrapper2(阵列<双> ^磅){ 的std ::矢量<双>低(LB->长度); { pin_ptr<双>销(安培;磅[0]); 性病::复制( 的static_cast<双*>(PIN), 的static_cast<双*>(销+ LB->长度), lower.begin() ); } _opt-> set_lower_bounds(低级);}
(人工范围是允许 pin_ptr
来尽早取消固定存储器,以便不妨碍由GC。)
Does anyone know of any easy way to convert a CLI/.NET System::array to a C++ std::vector, besides doing it element-wise?
I'm writing a wrapper method (SetLowerBoundsWrapper, below) in CLI/C++ that accepts a System::array as an argument, and passes the equivalent std::vector to a native C++ method (set_lower_bounds). Currently I do 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);
}
Another approach, letting the .NET BCL do the work instead of the C++ standard 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);
}
EDIT (in response to comments on Konrad's answer):
The following both compile for me with VC++ 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);
}
(The artificial scope is to allow the pin_ptr
to unpin the memory as early as possible, so as not to hinder the GC.)
这篇关于转换系统::阵列为std ::矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!