我有一个 C++ 函数计算一个大张量,我想通过pybind11作为 NumPy 数组返回 Python 。
从 pybind11 的文档来看,使用STL unique_ptr似乎是可取的。在下面的示例中,注释掉的版本有效,而给定的版本编译但在运行时失败(“无法将函数返回值转换为 Python 类型!”)。
为什么智能指针版本失败?创建和返回 NumPy 数组的规范方法是什么?
PS:由于程序结构和数组的大小,最好不要复制内存,而是从给定的指针创建数组。内存所有权应该由 Python 获得。
typedef typename py::array_t<double, py::array::c_style | py::array::forcecast> py_cdarray_t;
// py_cd_array_t _test()
std::unique_ptr<py_cdarray_t> _test()
{
double * memory = new double[3]; memory[0] = 11; memory[1] = 12; memory[2] = 13;
py::buffer_info bufinfo (
memory, // pointer to memory buffer
sizeof(double), // size of underlying scalar type
py::format_descriptor<double>::format(), // python struct-style format descriptor
1, // number of dimensions
{ 3 }, // buffer dimensions
{ sizeof(double) } // strides (in bytes) for each index
);
//return py_cdarray_t(bufinfo);
return std::unique_ptr<py_cdarray_t>( new py_cdarray_t(bufinfo) );
}