mirror of
https://github.com/pybind/pybind11.git
synced 2026-03-14 20:27:47 +00:00
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:
@@ -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
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user