16 Pickleable(
const std::string &
value) : m_value(
value) { }
17 const std::string &
value()
const {
return m_value; }
19 void setExtra1(
int extra1) { m_extra1 = extra1; }
20 void setExtra2(
int extra2) { m_extra2 = extra2; }
21 int extra1()
const {
return m_extra1; }
22 int extra2()
const {
return m_extra2; }
29 class PickleableNew :
public Pickleable {
31 using Pickleable::Pickleable;
34 py::class_<Pickleable> pyPickleable(
m,
"Pickleable");
36 .def(py::init<std::string>())
38 .def(
"extra1", &Pickleable::extra1)
39 .def(
"extra2", &Pickleable::extra2)
40 .def(
"setExtra1", &Pickleable::setExtra1)
41 .def(
"setExtra2", &Pickleable::setExtra2)
44 .def(
"__getstate__", [](
const Pickleable &p) {
50 .def(
"__setstate__", [](Pickleable &p, py::tuple t) {
52 throw std::runtime_error(
"Invalid state!");
54 new (&p) Pickleable(t[0].cast<std::string>());
57 p.setExtra1(t[1].cast<int>());
58 p.setExtra2(t[2].cast<int>());
62 py::class_<PickleableNew, Pickleable>(
m,
"PickleableNew")
63 .def(py::init<std::string>())
65 [](
const PickleableNew &p) {
70 throw std::runtime_error(
"Invalid state!");
71 auto p = PickleableNew(t[0].cast<std::string>());
73 p.setExtra1(t[1].cast<int>());
74 p.setExtra2(t[2].cast<int>());
79 #if !defined(PYPY_VERSION)
81 class PickleableWithDict {
89 class PickleableWithDictNew :
public PickleableWithDict {
91 using PickleableWithDict::PickleableWithDict;
94 py::class_<PickleableWithDict> pyPickleableWithDict(
m,
"PickleableWithDict", py::dynamic_attr());
96 .def(py::init<std::string>())
98 .def_readwrite(
"extra", &PickleableWithDict::extra)
99 .def(
"__getstate__", [](py::object
self) {
101 return py::make_tuple(
self.attr(
"value"),
self.attr(
"extra"),
self.attr(
"__dict__"));
105 .def(
"__setstate__", [](py::object
self, py::tuple t) {
107 throw std::runtime_error(
"Invalid state!");
109 auto& p =
self.cast<PickleableWithDict&>();
110 new (&p) PickleableWithDict(t[0].cast<std::string>());
113 p.extra = t[1].cast<
int>();
116 self.attr(
"__dict__") = t[2];
120 py::class_<PickleableWithDictNew, PickleableWithDict>(
m,
"PickleableWithDictNew")
121 .def(py::init<std::string>())
123 [](py::object
self) {
124 return py::make_tuple(
self.attr(
"value"),
self.attr(
"extra"),
self.attr(
"__dict__"));
126 [](
const py::tuple &t) {
128 throw std::runtime_error(
"Invalid state!");
130 auto cpp_state = PickleableWithDictNew(t[0].cast<std::string>());
131 cpp_state.extra = t[1].cast<
int>();
133 auto py_state = t[2].cast<py::dict>();
134 return std::make_pair(cpp_state, py_state);