Skip to content

Instantly share code, notes, and snippets.

@angus-g
Last active June 15, 2021 02:52
Show Gist options
  • Save angus-g/f52da7720d232f9bfefc2bcdf82f2aca to your computer and use it in GitHub Desktop.
Save angus-g/f52da7720d232f9bfefc2bcdf82f2aca to your computer and use it in GitHub Desktop.
/*
* higher-up library:
*/
class Foo {
std::shared_ptr<Vector<double>> v;
template<class Archive>
void serialize(Archive &archive) {
// defer polymorphic serialisation of Vector
archive(v);
}
};
/*
* binding code:
*/
// concrete functions for a pure virtual class
class PyVector : public Vector<double> {
public:
// a few methods like this:
virtual void plus(const Vector<double>& x) override {
PYBIND11_OVERRIDE_PURE(void, Vector<double>, plus, x);
}
template<class Archive>
void save(Archive &archive) const {
// cereal API for saving, e.g. serialise the pickle dump (untested!)
py::gil_scoped_acquire gil;
py::object pickle = py::module_::import("pickle");
py::object pickled = pickle.attr("dumps")(py::cast(this));
std::string result = pickled.cast<std::string>();
archive(result);
}
template<class Archive>
void load(Archive &archive) {
py::gil_scoped_acquire gil;
py::object pickle = py::module_::import("pickle");
std::string pickled;
archive(pickled); // load string
// un-pickle to python object
py::object loaded = pickle.attr("loads")(pickled);
// at this point, cereal already constructed our PyVector instance
// (through its polymorphism), but how do we tell it to "own" the
// un-pickled Python object?
}
};
CEREAL_REGISTER_POLYMORPHIC_RELATION(Vector<double>, PyVector);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment