How do I convert C++ vector to NumPy array using Boost.Python?
-
I have the following codes compiled successfully, but I get "Segmentation fault (core dumped)" in Python output. C++ part: boost::python::object stdVecToNumpyArray( std::vector<int>& vec ) { npy_intp size = vec.size(); PyObject *pyObj = PyArray_SimpleNewFromData(1, &size, NPY_INT, &vec[0]); boost::python::handle<> handle(pyObj); boost::python::numeric::array arr(handle); return arr.copy(); } class Data { public: Data(int n):data(n, 1) {} boost::python::object output() { return stdVecToNumpyArray(data); } private: std::vector<int> data; }; using namespace boost::python; BOOST_PYTHON_MODULE(plot) { class_<Data>("Data", init<int>()) .def("output", &Data::output); } Python part: from plot import * data = Data(10) print data.output()
-
Answer:
Here is the code I use : https://github.com/ndarray/Boost.NumPy So it would look something like namespace bp = boost::python; namespace bn = boost::numpy; class Data { public: Data(int n):data(bn::empty(bp::make_tuple(1),bn::dtype::get_builtin<int>())) { auto idx=0;//only one element *(reinterpret_cast<int* >(data.get_data())+idx)=n; } bp::object output() { return data; } private: bn::ndarray data; }; Of course you can add iterators and such to Data and make it loook more like a STL compatible container.
Lance Diduck at Quora Visit the source
Other answers
You need to initialize numpy in BOOST_PYTHON_MODULE() BOOST_PYTHON_MODULE(plot) { boost::python::numeric::array::set_module_and_type("numpy", "ndarray"); import_array(); class_<Data>("Data", init<int>()) .def("output", &Data::output); }
Pau Gargallo
Related Q & A:
- How do I convert a PDF file to PDF/A in Delphi?Best solution by softwarerecs.stackexchange.com
- How can I change a value in an array?Best solution by Stack Overflow
- How do I convert a bitmap to vector?Best solution by Super User
- How can I convert Matlab code to c#?Best solution by Stack Overflow
- How do I define the index within the array?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.