Suppose I have a simple class like this:
Entity.h
#include <pybind11/pybind11.h>
namespace py = pybind11;
class Entity {
public:
int *field;
Entity(const py::list& data);
~Entity();
}
Entity.cpp
#include "Entity.h"
Entity::Entity(const py::list& data) {
field = new int[py::len(data)];
for (int i = 0; i < length; i++) field[i] = py::int_(data[i]);
}
~Entity::Entity() { delete[] field; }
Now I bind it to Python with pybind11 like this:
Bind.cpp
#include "Entity.h"
PYBIND11_MODULE(Entity, module) {
py::class_<Entity>(module, "Entity")
.def(py::init<const py::list&>())
.def(py::pickle(
// Here I have no clue what to write
));
}
Pybind11 documentation suggests that the __getstate__ method be defined with py::make_tuple which should make a tuple with all the values of the attributes. The thing is, the value is a pointer, and all the data on the heap is deleted upon termination of the program.
How can I serialize an object with dynamically allocated attributes using pybind11?