2014-11-05 56 views
4

我有這個簡單的C++代碼:醃製助推器python中的矢量?

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) 
    { 
     return boost::python::make_tuple(c.my_vector); 
    } 
}; 

我試圖啓用CannotPickle這樣的酸洗支持:

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()); 

當我嘗試實際調用pickleCannotPickle我得到這個錯誤: RuntimeError:酸洗「MyModule.ContainedPtrList」實例未啓用(http://www.boost.org/libs/python/doc/v2/pickle.html

如何啓用酸洗vector_indexing_suite

回答

2

一些額外的搜索得到這個代碼,它似乎工作:

#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) 
    { 
     return py::make_tuple(); 
    } 

    static py::tuple getstate(py::object obj) 
    { 
     const std::vector<T>& o = py::extract<const std::vector<T>&>(obj)(); 

     return 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); 
    } 
};