如何使用模板和boost将矢量转换为numpy数组?

时间:2016-01-27 15:22:11

标签: 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();
}

1 个答案:

答案 0 :(得分:2)

您可以编写自己的特征,根据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());