c++ python交互之boost.python 简集之序列化(pickle)

c++代码:src.cpp

#include <string>
struct World
{
    World(std::string a_msg) : msg(a_msg) {}
    std::string greet() const { return msg; }
    std::string msg;
};

python转换代码:src4py.cpp

#include <boost/python.hpp>
#include "src.cpp"
using namespace boost::python;

struct World_picklers : pickle_suite
{
    static tuple
        getinitargs(World const& w) { return make_tuple(w.greet()); }
};

BOOST_PYTHON_MODULE(test)
{
    class_<World>("World", init<std::string>())
        .def("greet", &World::greet)
        .def_pickle(World_picklers())             //请关注这行的函数名,是固定的
        ;
}

 

python调用代码:test.py

import test
import pickle
a = test.World("haha")
pickle.dump(a,open("my_world","w"))
print "create pickle file(my_world)"

print "load from pickle file(my_world)"
b = pickle.load(open("my_world","r"))
print b.greet()

你可能感兴趣的:(C++,python,String,File,Module,Class)