pickle1.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. This example shows how to make an Extension Class "pickleable".
  6. The world class below can be fully restored by passing the
  7. appropriate argument to the constructor. Therefore it is sufficient
  8. to define the pickle interface method __getinitargs__.
  9. For more information refer to boost/libs/python/doc/pickle.html.
  10. */
  11. #include <boost/python/module.hpp>
  12. #include <boost/python/def.hpp>
  13. #include <boost/python/class.hpp>
  14. #include <boost/python/tuple.hpp>
  15. #include <string>
  16. namespace boost_python_test {
  17. // A friendly class.
  18. class world
  19. {
  20. private:
  21. std::string country;
  22. public:
  23. world(const std::string& _country) {
  24. this->country = _country;
  25. }
  26. std::string greet() const { return "Hello from " + country + "!"; }
  27. std::string get_country() const { return country; }
  28. };
  29. struct world_pickle_suite : boost::python::pickle_suite
  30. {
  31. static
  32. boost::python::tuple
  33. getinitargs(const world& w)
  34. {
  35. return boost::python::make_tuple(w.get_country());
  36. }
  37. };
  38. // To support test of "pickling not enabled" error message.
  39. struct noop {};
  40. }
  41. BOOST_PYTHON_MODULE(pickle1_ext)
  42. {
  43. using namespace boost::python;
  44. using namespace boost_python_test;
  45. class_<world>("world", init<const std::string&>())
  46. .def("greet", &world::greet)
  47. .def_pickle(world_pickle_suite())
  48. ;
  49. // To support test of "pickling not enabled" error message.
  50. class_<noop>("noop");
  51. }