Skip to content

Commit d31b16d

Browse files
committed
python-nb : Add pickle.hh, implement boost archive pickling
1 parent ebeb34c commit d31b16d

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

python-nb/math.cc

+2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
#include "fwd.h"
66
#include "serializable.hh"
7+
#include "pickle.hh"
78

89
#include <nanobind/eigen/dense.h>
910
#include <nanobind/stl/bind_vector.h>
@@ -54,6 +55,7 @@ void exposeMaths(nb::module_ &m) {
5455
.def(nb::self *= nb::self)
5556
.def(nb::self == nb::self)
5657
.def(nb::self != nb::self)
58+
.def(python::v2::PickleVisitor<Transform3s>())
5759
.def(python::v2::SerializableVisitor<Transform3s>());
5860

5961
nb::class_<Triangle>(m, "Triangle")

python-nb/pickle.hh

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include "fwd.h"
2+
3+
#include <boost/archive/text_oarchive.hpp>
4+
#include <boost/archive/text_iarchive.hpp>
5+
#include <sstream>
6+
7+
#include <nanobind/stl/string.h>
8+
9+
namespace coal::python {
10+
namespace v2 {
11+
12+
/// See: https://nanobind.readthedocs.io/en/latest/classes.html#pickling
13+
template <typename T>
14+
struct PickleVisitor : nb::def_visitor<PickleVisitor<T>> {
15+
template <class... Ts>
16+
void execute(nb::class_<T, Ts...> &cl) {
17+
using namespace nb::literals;
18+
cl.def("__getstate__", [](const T &obj) -> std::string {
19+
std::stringstream ss;
20+
boost::archive::text_oarchive oa(ss);
21+
oa & obj;
22+
return ss.str();
23+
}).def("__setstate__", [](T &obj, const std::string &state) {
24+
// placement-new
25+
std::istringstream is(state);
26+
boost::archive::text_iarchive ia(is, boost::archive::no_codecvt);
27+
ia >> obj;
28+
});
29+
}
30+
};
31+
32+
} // namespace v2
33+
} // namespace coal::python

0 commit comments

Comments
 (0)