Python 不带拷贝的二维向量pybind11数组
如何从pybind11中的向量向量创建2d numpy数组 我正在寻找一种快速完成这项工作的方法&无需复制(所以移动?),我希望以模板化的方式完成 到目前为止,我已经:Python 不带拷贝的二维向量pybind11数组,python,c++,numpy,pybind11,Python,C++,Numpy,Pybind11,如何从pybind11中的向量向量创建2d numpy数组 我正在寻找一种快速完成这项工作的方法&无需复制(所以移动?),我希望以模板化的方式完成 到目前为止,我已经: template< typename T > py::array array2d_from_vector(std::vector<std::vector<T>> & m) { if (m.empty()) return py::array_t<T>(); s
template< typename T >
py::array
array2d_from_vector(std::vector<std::vector<T>> & m) {
if (m.empty()) return py::array_t<T>();
std::vector<std::vector<T>>* ptr = new std::vector<std::vector<T>>(std::move(m));
auto capsule = py::capsule(ptr, [](void* p) {
delete reinterpret_cast<std::vector<std::vector<T>>*>(p);
});
return py::array_t<T>(
{ptr->size(), ptr->at(0).size()}, // shape of array
{ptr->at(0).size()*sizeof(T), sizeof(T)}, // c-style contiguous strides
capsule);
}
那么我错过了什么!我猜这与向量保存数据的方式有关,但我的值应该在0到1之间。pybind11如何存储2d
numpy
将值存储在1d C数组(缓冲区)中,并使用形状和步幅将其视为2d。如果您的源代码使用向量向量方法(1层或多层嵌套指针),则不能将其用作numpy
数据缓冲区。到目前为止,我得到的最快的是一个'reserve'+insert(vec.end()..)调用,但我希望它能快一点…:/
[[ 4.0852747e+30 3.0677226e-41 4.0853762e+30 3.0677226e-41]...