指针的std :: array或std :: vector [英] std::array or std::vector from pointer
问题描述
我在C ++ / CLI数组中有一个数据数组,可以使用 pin_ptr< T>
传递给本机函数,到目前为止没有问题。但是,现在,我需要将该数组传递给C ++ / STL函数,该函数需要一个容器,例如 std :: array
或 std ::向量
。
I have an array of data in a C++/CLI array that I can pass to a native function using pin_ptr<T>
, no problem so far. Now, however, I need to pass the array on to a C++/STL function that expects a container such as std::array
or std::vector
.
最简单的方法(我首先做过)是逐个元素地复制。
The easy way of doing this (which I did first), is to copy element by element.
第二种最简单的方法是调用 std :: copy()
,请参见以下问题的答案:将System :: array转换为std :: vector 。
The second-easiest way is to call std::copy()
, see the answer to this question: convert System::array to std::vector.
但是,我想跳过整个复制步骤,而只使用指针。看到 std :: array
需要一个模板参数来确定其长度,我无法在运行时创建一个(但如果我输入错了,请更正我)。有没有一种方法可以创建矢量或其他类型的STL容器,而无需不必要的数据复制?
However, I want to skip the entire copying step and just use the pointer instead. Seeing as std::array
requires a template argument to determine its length, I can't create one at runtime (but please do correct me if I'm wrong). Is there a way to create a vector or a different type of STL container, without unnecessary copying of data?
推荐答案
由于C + +20有一种方法可以将c ++容器与c ++ / cli中的托管数组一起使用,避免复制数据: std :: span
Since C++20 there is a way to use c++ containers with managed arrays in c++/cli that avoids copying the data: std::span
在c ++ 20中,可以使用 std :: span
包装托管的c ++ / cli数组。然后,它可以与标准容器算法一起使用。
In c++20 it's possible to use std::span
to wrap a managed c++/cli array. Then it can be used with standard container algorithms.
不幸的是,Microsoft不支持c ++ / cli而不是c ++ 17。因此,必须先将指针和长度传递给另一个使用c ++ latest编译的源文件中的函数,同时使用较早的c ++ 17 / cli编译调用方的源文件。幸运的是,ABI是兼容的。可以在Visual Studio 2019的属性页中为每个文件轻松设置。
Unfortunately, Microsoft doesn't support c++/cli beyond c++17. Consequently one must first pass the pointer and length to a function in a different source file that is compiled using c++latest while compiling the caller's source file using the earlier c++17/cli. Fortunately the ABIs are compatible. This is easily set up for each file in the properties page of Visual Studio 2019.
下面是一些示例代码,它们创建了一个小的托管 array< double>
然后调用一个函数,该函数使用 std :: span
包装托管数据,然后使用 std :: sort
Here's some sample code that creates a small managed array<double>
then calls a function that wraps the managed data with std::span
then sorts with std::sort
// file1.cpp compile with /cli
#include <iostream>
using namespace System;
void sortme(double *p, int len);
int main()
{
array<double>^ v = gcnew array<double> {1.0, 3.0, 2.0, 4.0};
pin_ptr<double> pin=&v[0];
int len=v->Length;
sortme(pin, len);
for (int i = 0; i < len; i++)
std::cout << v[i] << "\n"; // prints sorted array
}
// file2.cpp compile with c++latest
#include <span>
#include <algorithm>
void sortme(double *p, int len)
{
std::span data_clr(p, len);
std::sort(data_clr.begin(), data_clr.end());
}
这篇关于指针的std :: array或std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!