How to create a numpy array from C++ side and give that to python?
I want Python to do the clean up when the returned array is no longer used by Python.
C++ side would not use delete ret; to free the memory allocated by new double[size];.
Is the following correct?
#include "pybind11/pybind11.h"
#include "pybind11/numpy.h"
namespace py = pybind11;
py::array_t<double> make_array(const py::ssize_t size) {
    double* ret = new double[size];
    return py::array(size, ret);
}
PYBIND11_MODULE(my_module, m) {
    .def("make_array", &make_array,
         py::return_value_policy::take_ownership);
}
                Your are quite correct. A little better solution is below.
#include "pybind11/pybind11.h"
#include "pybind11/numpy.h"
namespace py = pybind11;
py::array_t<double> make_array(const py::ssize_t size) {
    // No pointer is passed, so NumPy will allocate the buffer
    return py::array_t<double>(size);
}
PYBIND11_MODULE(my_module, m) {
    .def("make_array", &make_array,
         py::return_value_policy::move); // Return policy can be left default, i.e. return_value_policy::automatic
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With