So I found how to return numpy.array from boost::python? . However, like this I have to write this function for int, float, double separately. Is it possible to avoid this using templates? I would somehow need to convert with T to an entry to the enumeration of NPY data types. Or are there other options?
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();
}
You can write your own trait which will select numpy type based on c++ type, for example:
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;
};
And then:
PyObject* obj = PyArray_SimpleNewFromData(1, shape, select_npy_type<T>::type, vector.data());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.