| 58 | } // namespace exercise_trampoline |
| 59 | |
| 60 | TEST_SUBMODULE(pickling, m) { |
| 61 | m.def("simple_callable", []() { return 20220426; }); |
| 62 | |
| 63 | // test_roundtrip |
| 64 | class Pickleable { |
| 65 | public: |
| 66 | explicit Pickleable(const std::string &value) : m_value(value) {} |
| 67 | const std::string &value() const { return m_value; } |
| 68 | |
| 69 | void setExtra1(int extra1) { m_extra1 = extra1; } |
| 70 | void setExtra2(int extra2) { m_extra2 = extra2; } |
| 71 | int extra1() const { return m_extra1; } |
| 72 | int extra2() const { return m_extra2; } |
| 73 | |
| 74 | private: |
| 75 | std::string m_value; |
| 76 | int m_extra1 = 0; |
| 77 | int m_extra2 = 0; |
| 78 | }; |
| 79 | |
| 80 | class PickleableNew : public Pickleable { |
| 81 | public: |
| 82 | using Pickleable::Pickleable; |
| 83 | }; |
| 84 | |
| 85 | py::class_<Pickleable> pyPickleable(m, "Pickleable"); |
| 86 | pyPickleable.def(py::init<std::string>()) |
| 87 | .def("value", &Pickleable::value) |
| 88 | .def("extra1", &Pickleable::extra1) |
| 89 | .def("extra2", &Pickleable::extra2) |
| 90 | .def("setExtra1", &Pickleable::setExtra1) |
| 91 | .def("setExtra2", &Pickleable::setExtra2) |
| 92 | // For details on the methods below, refer to |
| 93 | // http://docs.python.org/3/library/pickle.html#pickling-class-instances |
| 94 | .def("__getstate__", [](const Pickleable &p) { |
| 95 | /* Return a tuple that fully encodes the state of the object */ |
| 96 | return py::make_tuple(p.value(), p.extra1(), p.extra2()); |
| 97 | }); |
| 98 | ignoreOldStyleInitWarnings([&pyPickleable]() { |
| 99 | pyPickleable.def("__setstate__", [](Pickleable &p, const py::tuple &t) { |
| 100 | if (t.size() != 3) { |
| 101 | throw std::runtime_error("Invalid state!"); |
| 102 | } |
| 103 | /* Invoke the constructor (need to use in-place version) */ |
| 104 | new (&p) Pickleable(t[0].cast<std::string>()); |
| 105 | |
| 106 | /* Assign any additional state */ |
| 107 | p.setExtra1(t[1].cast<int>()); |
| 108 | p.setExtra2(t[2].cast<int>()); |
| 109 | }); |
| 110 | }); |
| 111 | |
| 112 | py::class_<PickleableNew, Pickleable>(m, "PickleableNew") |
| 113 | .def(py::init<std::string>()) |
| 114 | .def(py::pickle( |
| 115 | [](const PickleableNew &p) { |
| 116 | return py::make_tuple(p.value(), p.extra1(), p.extra2()); |
| 117 | }, |
nothing calls this directly
no test coverage detected