<p><strong>c++代码:src.cpp</strong>
</p>
<p>#include <string><br>
struct World<br>
{<br>
World(std::string a_msg) : msg(a_msg) {}<br>
std::string greet() const { return msg; }<br>
std::string msg;<br>
};<br><br><strong>python转换代码:src4py.cpp</strong>
</p>
<p>#include <boost/python.hpp><br>
#include "src.cpp"<br>
using namespace boost::python;<br><br>
struct World_picklers : pickle_suite<br>
{<br>
static tuple<br>
getinitargs(World const& w) { return make_tuple(w.greet()); }<br>
};<br><br>
BOOST_PYTHON_MODULE(test)<br>
{<br>
class_<World>("World", init<std::string>())<br>
.def("greet", &World::greet)<br>
.def_pickle(World_picklers())<strong> //请关注这行的函数名,是固定的</strong>
<br>
;<br>
}</p>
<p></p>
<p><strong>python调用代码:test.py</strong>
</p>
<p>import test<br>
import pickle<br>
a = test.World("haha")<br>
pickle.dump(a,open("my_world","w"))<br>
print "create pickle file(my_world)" <br><br>
print "load from pickle file(my_world)"<br>
b = pickle.load(open("my_world","r"))<br>
print b.greet()<br><br></p>
</p>
<p>#include <string><br>
struct World<br>
{<br>
World(std::string a_msg) : msg(a_msg) {}<br>
std::string greet() const { return msg; }<br>
std::string msg;<br>
};<br><br><strong>python转换代码:src4py.cpp</strong>
</p>
<p>#include <boost/python.hpp><br>
#include "src.cpp"<br>
using namespace boost::python;<br><br>
struct World_picklers : pickle_suite<br>
{<br>
static tuple<br>
getinitargs(World const& w) { return make_tuple(w.greet()); }<br>
};<br><br>
BOOST_PYTHON_MODULE(test)<br>
{<br>
class_<World>("World", init<std::string>())<br>
.def("greet", &World::greet)<br>
.def_pickle(World_picklers())<strong> //请关注这行的函数名,是固定的</strong>
<br>
;<br>
}</p>
<p></p>
<p><strong>python调用代码:test.py</strong>
</p>
<p>import test<br>
import pickle<br>
a = test.World("haha")<br>
pickle.dump(a,open("my_world","w"))<br>
print "create pickle file(my_world)" <br><br>
print "load from pickle file(my_world)"<br>
b = pickle.load(open("my_world","r"))<br>
print b.greet()<br><br></p>