所以我找到了how to return numpy.array from boost::python? .但是,像这样我必须分别为 int、float、double 编写这个函数。是否可以使用模板避免这种情况?我会以某种方式需要使用 T 转换为 NPY 数据类型枚举的条目。或者还有其他选择吗?
template<typename T>
boost::python::object getNumpyArray(std::vector<T>& vector)
{
npy_intp shape[1] = { vector.size() };
//Here I would need to replace NPY_DOUBLE with some conversion of T
PyObject* obj = PyArray_SimpleNewFromData(1, shape, NPY_DOUBLE, vector.data());
boost::python::handle<> handle(obj);
boost::python::numeric::array arr(handle);
return arr.copy();
}
最佳答案
您可以编写自己的 trait,它会根据 c++ 类型选择 numpy 类型,例如:
template <typename T>
struct select_npy_type
{};
template <>
struct select_npy_type<double>
{
const static NPY_TYPES type = NPY_DOUBLE;
};
template <>
struct select_npy_type<float>
{
const static NPY_TYPES type = NPY_FLOAT;
};
template <>
struct select_npy_type<int>
{
const static NPY_TYPES type = NPY_INT;
};
然后:
PyObject* obj = PyArray_SimpleNewFromData(1, shape, select_npy_type<T>::type, vector.data());
关于python - 如何使用模板和 boost 将 vector 转换为 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35041268/