#include <boost/python.hpp> #include <boost/python/numeric.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <iostream> #include <vector> namespace bp = boost::python; int main() { Py_Initialize(); bp::object main = bp::import("__main__"); bp::object namesp = main.attr("__dict__"); bp::numeric::array::set_module_and_type("numpy", "ndarray"); // use numpy.ndarray as numeric::array bp::class_<std::vector<int> > ("PyVecInt") .def(bp::vector_indexing_suite<std::vector<int> > () ); // tell python how to access the vector std::vector<int> vec; for(int i=0; i<20; i++) vec.push_back(i); bp::numeric::array ary(vec); // vector -> ndarray ary.resize(bp::make_tuple(4, 5)); namesp["pyary"] = ary; // c++ binary --> python interpreter exec("print pyary", namesp); exec("print pyary.shape", namesp); exec("print type(pyary)", namesp); }
すると、次のような結果が得られる.
[[ 0 1 4 9 16] [ 25 36 49 64 81] [100 121 144 169 196] [225 256 289 324 361]] (4, 5) <type 'numpy.ndarray'>
等価な python code
#equivalent python code import numpy pyary = numpy.array(range(20)) pyary.resize(4, 5) print pyary print pyary.shape print type(pyary)
0 件のコメント:
コメントを投稿