12

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);
}
1
  • I have to use the numpy instead of eigen interface of pybind11 because I use a structured numpy array. Commented Mar 8, 2018 at 18:25

1 Answer 1

16

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
}
Sign up to request clarification or add additional context in comments.

5 Comments

hmm. And this won't make a copy? I am checking if py::array_t has a move constructor.... It seems to have one here: github.com/pybind/pybind11/blob/…
Sure it will not make a copy due to return value optimization and copy elision.
The casting for py::return_value_policy::move is here: github.com/pybind/pybind11/blob/… Thanks.
Really really wish they talk about this in the official documentation...
Does py::array_t initialize the newly allocated buffer? Or should we initialize it ourselves?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.