2016-01-27 22 views
0

所以我找到how to return numpy.array from boost::python?。但是,像這樣,我必須分別爲int,float和double編寫這個函數。使用模板可以避免這種情況嗎?我會不知何故需要用T轉換爲NPY數據類型枚舉的入口。或者還有其他選擇嗎?如何將矢量轉換爲具有模板和提升的numpy數組?

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(); 
} 
+0

相關的/重複數據刪除技術:HTTP:// stackoverflow.com/questions/16065183/convert-a-stdvector-to-a-numpy-array-without-copying-data – NathanOliver

+0

@NathanOliver您鏈接到的問題(或至少答案)幾乎與我鏈接的問題相同但沒有提供任何有關如何emp的信息使用'PyArray_SimpleNewFromData'避免代碼複製粘貼模板,這基本上是我的問題。所以我認爲我的問題不是重複的。 – NOhs

回答

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()); 
相關問題