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


本文转自elbertchen 51CTO博客,原文链接:http://blog.51cto.com/linkyou/751836,如需转载请自行联系原作者
上一篇:#define与typedef区别


下一篇:LINUX下的crontab计划任务