在Boost Python中腌制矢量? [英] Pickling a vector in boost python?

查看:70
本文介绍了在Boost Python中腌制矢量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的C ++代码:

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

我正在尝试启用对 CannotPickle 的酸洗支持,如下所示:

I'm trying to enable pickling support for CannotPickle like 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());

当我尝试在 CannotPickle 上实际调用 pickle 时,出现此错误:RuntimeError:"MyModule.ContainedPtrList"实例的酸洗未启用( http://www.boost.org/libs/python/doc/v2/pickle.html )

When I try to actually call pickle on a CannotPickle I get this error: RuntimeError: Pickling of "MyModule.ContainedPtrList" instances is not enabled (http://www.boost.org/libs/python/doc/v2/pickle.html)

如何为 vector_indexing_suite 启用酸洗?

推荐答案

一些其他搜索产生了此代码,该代码似乎可行:

Some additional searching yielded this code, which seems to 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)
    {
        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);
    }
};

这篇关于在Boost Python中腌制矢量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆