Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost.Serialization and Boost.Python two-way pickle

I have a C++ library that uses Boost.Serialization. I'm creating Python bindings for this library using Boost.Python. It's fairly clear how to make a pickle suite for Boost.Python that uses Boost.Serialization (save to a string using Boost.Serialization, and return that string to Python).

What I want is the reverse: given a boost::python::object, I want to have a serialize(...) function that would call Python's pickle.dumps() function and serialize the resulting string. (Imagine an std::vector<boost::python::object>. As I serialize this vector, Boost.Serialization would call the auxiliary serialize() function.) Is this possible? Better yet, is it possible to use cPickle and bypass giving the control to the Python interpreter?

like image 275
foxcub Avatar asked Sep 02 '11 22:09

foxcub


1 Answers

Here is the code I use to pickle/unpickle instance of boost::mersenne_twister

typedef boost::mt19937 rng_t;

struct mt_pickle_suite : bp::pickle_suite {

  static bp::object getstate (const rng_t& rng) {
    std::ostringstream os;
    boost::archive::binary_oarchive oa(os);
    oa << rng;
    return bp::str (os.str());
  }

static void
  setstate(rng_t& rng, bp::object entries) {
    bp::str s = bp::extract<bp::str> (entries)();
    std::string st = bp::extract<std::string> (s)();
    std::istringstream is (st);

    boost::archive::binary_iarchive ia (is);
    ia >> rng;
  }
};
like image 155
nbecker Avatar answered Sep 22 '22 05:09

nbecker