You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.8 KiB

  1. /*
  2. example/example15.cpp -- pickle support
  3. Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #include "example.h"
  8. class Pickleable {
  9. public:
  10. Pickleable(const std::string &value) : m_value(value) { }
  11. const std::string &value() const { return m_value; }
  12. void setExtra1(int extra1) { m_extra1 = extra1; }
  13. void setExtra2(int extra2) { m_extra2 = extra2; }
  14. int extra1() const { return m_extra1; }
  15. int extra2() const { return m_extra2; }
  16. private:
  17. std::string m_value;
  18. int m_extra1 = 0;
  19. int m_extra2 = 0;
  20. };
  21. void init_ex15(py::module &m) {
  22. py::class_<Pickleable>(m, "Pickleable")
  23. .def(py::init<std::string>())
  24. .def("value", &Pickleable::value)
  25. .def("extra1", &Pickleable::extra1)
  26. .def("extra2", &Pickleable::extra2)
  27. .def("setExtra1", &Pickleable::setExtra1)
  28. .def("setExtra2", &Pickleable::setExtra2)
  29. // For details on the methods below, refer to
  30. // http://docs.python.org/3/library/pickle.html#pickling-class-instances
  31. .def("__getstate__", [](const Pickleable &p) {
  32. /* Return a tuple that fully encodes the state of the object */
  33. return py::make_tuple(p.value(), p.extra1(), p.extra2());
  34. })
  35. .def("__setstate__", [](Pickleable &p, py::tuple t) {
  36. if (t.size() != 3)
  37. throw std::runtime_error("Invalid state!");
  38. /* Invoke the constructor (need to use in-place version) */
  39. new (&p) Pickleable(t[0].cast<std::string>());
  40. /* Assign any additional state */
  41. p.setExtra1(t[1].cast<int>());
  42. p.setExtra2(t[2].cast<int>());
  43. });
  44. }