• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 boost_python_test {
23 
24   // A friendly class.
25   class world
26   {
27     private:
28       std::string country;
29     public:
world(const std::string & _country)30       world(const std::string& _country) {
31         this->country = _country;
32       }
greet() const33       std::string greet() const { return "Hello from " + country + "!"; }
get_country() const34       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
getinitargsboost_python_test::world_pickle_suite41     getinitargs(const world& w)
42     {
43         return boost::python::make_tuple(w.get_country());
44     }
45   };
46 
47   // To support test of "pickling not enabled" error message.
48   struct noop {};
49 }
50 
BOOST_PYTHON_MODULE(pickle1_ext)51 BOOST_PYTHON_MODULE(pickle1_ext)
52 {
53   using namespace boost::python;
54   using namespace boost_python_test;
55   class_<world>("world", init<const std::string&>())
56       .def("greet", &world::greet)
57       .def_pickle(world_pickle_suite())
58       ;
59 
60   // To support test of "pickling not enabled" error message.
61   class_<noop>("noop");
62 }
63