jiminy
jiminy copied to clipboard
[core/python] Add a way to take ownership when converting to python
The point is to avoid copy when wrapping temporaries, which typically happens the case when parsing log files here and wrapping some methods. Consider using boost::python::numpy
instead raw C-Python API calls for constructing numpy object. It may be easier to expose a new take_ownership
attribute for numpy converters. Otherwise, set ownership manually by doing:
void destroyManagedCObject(void * capsule) {
free(PyCapsule_GetPointer(capsule, NULL));
};
PyObject * obj = PyCapsule_New(buffer, NULL, static_cast<PyCapsule_Destructor>(&destroyManagedCObject));
PyArray_SetBaseObject(static_cast<PyArrayObject *>(array), obj)
Note that taking ownership it not going to be helpful if memory has been allocated on the stack and not on the heap. It should be fine for dynamic size Eigen objects but not for fixed size. Fortunately, It is easy to detect this edge-case at compile-time.
See also for reference:
- https://stackoverflow.com/questions/37575412/can-boostpython-pass-ownership-of-an-object-to-a-python-callback-function
- https://stackoverflow.com/questions/57068443/setting-owner-in-boostpythonndarray-so-that-data-is-owned-and-managed-by-pyt
- https://github.com/boostorg/python/issues/97