Pybind11: Creating an array which owns its data

Created on 26 Feb 2020  路  3Comments  路  Source: pybind/pybind11

Hi,

I've run into the following issue while wrapping some legacy C++ code:

The C++ code creates an array through a naked new[]. My understanding is that I can expose this data to Python by invoking the array_t constructor with a buffer_info which has the ptr set to the array.

However, what if I would like the array to take ownership of that data, i.e., delete it when it gets destroyed? Is that possible with array_t or do I need to write my own array wrapper with ownership semantics?

Most helpful comment

Thanks, I saw some similar approaches on SO in the meantime.

This should really be documented or at the very least a FAQ with a SO link.

All 3 comments

It is not documented, but you do this via a capsule/deleter combo. Here are (GPL3) examples from a project of mine: https://github.com/molpopgen/fwdpy11/blob/master/fwdpy11/headers/fwdpy11/numpy/array.hpp

Thanks, I saw some similar approaches on SO in the meantime.

This should really be documented or at the very least a FAQ with a SO link.

Yes, it should be documented better, probably.
Let's close this issue and keep #1042 open to remind ourselves to do this.

Was this page helpful?
0 / 5 - 0 ratings