| [29] | 1 | // Copyright Ralf W. Grosse-Kunstleve 2002-2004. Distributed under the Boost |
|---|
| 2 | // Software License, Version 1.0. (See accompanying |
|---|
| 3 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
|---|
| 4 | |
|---|
| 5 | /* |
|---|
| 6 | This example shows how to make an Extension Class "pickleable". |
|---|
| 7 | |
|---|
| 8 | The world class below can be fully restored by passing the |
|---|
| 9 | appropriate argument to the constructor. Therefore it is sufficient |
|---|
| 10 | to define the pickle interface method __getinitargs__. |
|---|
| 11 | |
|---|
| 12 | For more information refer to boost/libs/python/doc/pickle.html. |
|---|
| 13 | */ |
|---|
| 14 | |
|---|
| 15 | #include <boost/python/module.hpp> |
|---|
| 16 | #include <boost/python/def.hpp> |
|---|
| 17 | #include <boost/python/class.hpp> |
|---|
| 18 | #include <boost/python/tuple.hpp> |
|---|
| 19 | |
|---|
| 20 | #include <string> |
|---|
| 21 | |
|---|
| 22 | namespace { |
|---|
| 23 | |
|---|
| 24 | // A friendly class. |
|---|
| 25 | class world |
|---|
| 26 | { |
|---|
| 27 | private: |
|---|
| 28 | std::string country; |
|---|
| 29 | public: |
|---|
| 30 | world(const std::string& country) { |
|---|
| 31 | this->country = country; |
|---|
| 32 | } |
|---|
| 33 | std::string greet() const { return "Hello from " + country + "!"; } |
|---|
| 34 | std::string get_country() const { return country; } |
|---|
| 35 | }; |
|---|
| 36 | |
|---|
| 37 | struct world_pickle_suite : boost::python::pickle_suite |
|---|
| 38 | { |
|---|
| 39 | static |
|---|
| 40 | boost::python::tuple |
|---|
| 41 | getinitargs(const world& w) |
|---|
| 42 | { |
|---|
| 43 | using namespace boost::python; |
|---|
| 44 | return make_tuple(w.get_country()); |
|---|
| 45 | } |
|---|
| 46 | }; |
|---|
| 47 | |
|---|
| 48 | } |
|---|
| 49 | |
|---|
| 50 | BOOST_PYTHON_MODULE(pickle1_ext) |
|---|
| 51 | { |
|---|
| 52 | using namespace boost::python; |
|---|
| 53 | class_<world>("world", init<const std::string&>()) |
|---|
| 54 | .def("greet", &world::greet) |
|---|
| 55 | .def_pickle(world_pickle_suite()) |
|---|
| 56 | ; |
|---|
| 57 | } |
|---|