Last active
June 15, 2021 02:52
-
-
Save angus-g/f52da7720d232f9bfefc2bcdf82f2aca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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