python - 如何使用模板和 boost 将 vector 转换为 numpy 数组?

标签 python c++ numpy boost

所以我找到了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/

相关文章:

python - 不同长度的numpy数组的KL分歧

python - 如何将 1D numpy 数组分配给 2D numpy 数组?

Python 3 - Win 8 上的 Django 1.7 - MySQL 连接问题

python - 类型提示、与前向引用的联合

c++ long double 精确打印所有数字

c++ - OpenCV 错误:断言失败 ((unsigned)i0 < (unsigned)size.p[0]) in cv::Mat::at

Python - 迭代和更改列表的元素

python - 我如何在Python中交换矩阵中的列表?

c++ - 没有运算符 "=="处理这些操作数

python - 查找 Pandas 列子集中的最大值和第二个最大值之间的差异