c++ - Pickling a vector in boost python? -
c++ - Pickling a vector in boost python? -
i have simple c++ code:
class contained {}; class cannotpickle { public: cannotpickle() {}; cannotpickle(std::vector<boost::shared_ptr<contained>> new_vector) : my_vector(new_vector) {}; std::vector<boost::shared_ptr<contained>> my_vector; }; struct cannotpickle_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(cannotpickle const& c) { homecoming boost::python::make_tuple(c.my_vector); } };
i'm trying enable pickling back upwards cannotpickle
this:
class_<contained>("contained"); class_<std::vector<boost::shared_ptr<contained>>>("containedptrlist") .def(vector_indexing_suite<std::vector<boost::shared_ptr<contained>>, true>()); class_<cannotpickle>("cannotpickle") .def_pickle(cannotpickle_pickle_suite());
when seek phone call pickle
on cannotpickle
error: runtimeerror: pickling of "mymodule.containedptrlist" instances not enabled (http://www.boost.org/libs/python/doc/v2/pickle.html)
how can enable pickling vector_indexing_suite
?
some additional searching yielded code, seems work:
#include <vector> #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <boost/smart_ptr.hpp> namespace py = boost::python; template <class c> struct picklesuite: public py::pickle_suite { boost_static_assert(sizeof(c)==0); }; template <typename t> struct picklesuite< std::vector<t> >: public py::pickle_suite { static py::tuple getinitargs(const std::vector<t>& o) { homecoming py::make_tuple(); } static py::tuple getstate(py::object obj) { const std::vector<t>& o = py::extract<const std::vector<t>&>(obj)(); homecoming py::make_tuple(py::list(o)); } static void setstate(py::object obj, py::tuple state) { std::vector<t>& o = py::extract<std::vector<t>&>(obj)(); py::stl_input_iterator<typename std::vector<t>::value_type> begin(state[0]), end; o.insert(o.begin(),begin,end); } };
python c++ boost vector pickle
Comments
Post a Comment