R zu
R zu

Reputation: 2074

Pybind11: Create and return numpy array from C++ side

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);
}

Upvotes: 12

Views: 10387

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38528

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
}

Upvotes: 16

Related Questions