|
| 1 | +// clang-format off |
1 | 2 | /*
|
2 | 3 | tests/test_pickling.cpp -- pickle support
|
3 | 4 |
|
4 | 5 | Copyright (c) 2016 Wenzel Jakob <[email protected]>
|
| 6 | + Copyright (c) 2021 The Pybind Development Team. |
5 | 7 |
|
6 | 8 | All rights reserved. Use of this source code is governed by a
|
7 | 9 | BSD-style license that can be found in the LICENSE file.
|
8 | 10 | */
|
9 | 11 |
|
10 | 12 | #include "pybind11_tests.h"
|
11 | 13 |
|
| 14 | +// clang-format on |
| 15 | + |
| 16 | +#include <memory> |
| 17 | +#include <stdexcept> |
| 18 | +#include <utility> |
| 19 | + |
| 20 | +namespace exercise_trampoline { |
| 21 | + |
| 22 | +struct SimpleBase { |
| 23 | + int num = 0; |
| 24 | + virtual ~SimpleBase() = default; |
| 25 | + |
| 26 | + // For compatibility with old clang versions: |
| 27 | + SimpleBase() = default; |
| 28 | + SimpleBase(const SimpleBase &) = default; |
| 29 | +}; |
| 30 | + |
| 31 | +struct SimpleBaseTrampoline : SimpleBase {}; |
| 32 | + |
| 33 | +struct SimpleCppDerived : SimpleBase {}; |
| 34 | + |
| 35 | +void wrap(py::module m) { |
| 36 | + py::class_<SimpleBase, SimpleBaseTrampoline>(m, "SimpleBase") |
| 37 | + .def(py::init<>()) |
| 38 | + .def_readwrite("num", &SimpleBase::num) |
| 39 | + .def(py::pickle( |
| 40 | + [](py::object self) { |
| 41 | + py::dict d; |
| 42 | + if (py::hasattr(self, "__dict__")) |
| 43 | + d = self.attr("__dict__"); |
| 44 | + return py::make_tuple(self.attr("num"), d); |
| 45 | + }, |
| 46 | + [](py::tuple t) { |
| 47 | + if (t.size() != 2) |
| 48 | + throw std::runtime_error("Invalid state!"); |
| 49 | + auto cpp_state = std::unique_ptr<SimpleBase>(new SimpleBaseTrampoline); |
| 50 | + cpp_state->num = t[0].cast<int>(); |
| 51 | + auto py_state = t[1].cast<py::dict>(); |
| 52 | + return std::make_pair(std::move(cpp_state), py_state); |
| 53 | + })); |
| 54 | + |
| 55 | + m.def("make_SimpleCppDerivedAsBase", |
| 56 | + []() { return std::unique_ptr<SimpleBase>(new SimpleCppDerived); }); |
| 57 | +} |
| 58 | + |
| 59 | +} // namespace exercise_trampoline |
| 60 | + |
| 61 | +// clang-format off |
| 62 | + |
12 | 63 | TEST_SUBMODULE(pickling, m) {
|
13 | 64 | // test_roundtrip
|
14 | 65 | class Pickleable {
|
@@ -130,4 +181,6 @@ TEST_SUBMODULE(pickling, m) {
|
130 | 181 | return std::make_pair(cpp_state, py_state);
|
131 | 182 | }));
|
132 | 183 | #endif
|
| 184 | + |
| 185 | + exercise_trampoline::wrap(m); |
133 | 186 | }
|
0 commit comments