如何将System :: array转换为std :: vector? [英] How to convert System::array to std::vector?
问题描述
有没有简单的方法可以将CLI / .NET System :: array
转换为C ++ std :: vector
,除了按元素进行操作外?
Is there any easy way to convert a CLI/.NET System::array
to a C++ std::vector
, besides doing it element-wise?
我正在编写包装方法( SetLowerBoundsWrapper,在
下面)在CLI / C ++中,它接受 System :: array
作为参数,并将等效的 std :: vector
传递给原生C ++方法( set_lower_bounds
)。目前,我的操作如下:
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);
}
推荐答案
另一种方法是让。 NET BCL代替C ++标准库来工作:
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);
}
以下两者均针对我使用VC ++ 2010 SP1,并且完全等效:
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);
}
人为的范围是允许 pin_ptr
尽早取消固定内存,以免妨碍GC。
The artificial scope is to allow the pin_ptr
to unpin the memory as early as possible, so as not to hinder the GC.
这篇关于如何将System :: array转换为std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!