Permit creation of NumPy arrays with a "base" object that owns the data

This patch adds an extra base handle parameter to most ``py::array`` and
``py::array_t<>`` constructors. If specified along with a pointer to
data, the base object will be registered within NumPy, which increases
the base's reference count. This feature is useful to create shallow
copies of C++ or Python arrays while ensuring that the owners of the
underlying can't be garbage collected while referenced by NumPy.

The commit also adds a simple test function involving a ``wrap()``
function that creates shallow copies of various N-D arrays.
This commit is contained in:
Wenzel Jakob
2016-10-13 00:57:42 +02:00
parent 43f6aa6846
commit 369e9b3937
3 changed files with 124 additions and 24 deletions

View File

@@ -99,4 +99,14 @@ test_initializer numpy_array([](py::module &m) {
sm.def("make_c_array", [] {
return py::array_t<float>({ 2, 2 }, { 8, 4 });
});
sm.def("wrap", [](py::array a) {
return py::array(
a.dtype(),
std::vector<size_t>(a.shape(), a.shape() + a.ndim()),
std::vector<size_t>(a.strides(), a.strides() + a.ndim()),
a.data(),
a
);
});
});