Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 830
R zu Avatar asked Mar 08 '18 17:03

R zu


1 Answers

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
}
like image 81
273K Avatar answered Oct 20 '22 05:10

273K