'Cast pybind11::array_t to mutable std::vector

I have a simple C++ class that I want to expose to Python using Pybind11. Problem is that the void C++ function accepts std::vector & inputs, and pybind11::array_t are immutable. Therefore I do not get modified vector out.

example: C++ program

#include<pybind11/numpy.h>
#include<pybind11/pybind11.h>
#include<pybind11/stl.h>
#include<vector>

using namespace std;
namespace py=pybind11;

class SimpleClass{
public:
double const_double;
void sum(vector<double> & in_arr, vector<double> & out_arr){
    for (int i = 0; i < in_arr.size();i++){
        out_arr[i] = in_arr[i] + const_double;
    }
}};

PYBIND11_MODULE(simple, m){
    py::class_<SimpleClass>(m, "SimpleClass")
    .def(py::init<>())
    .def_readwrite("dat",&SimpleClass::const_double)
    .def("sum_lambda",[](
        SimpleClass & sc,
        vector<double> & in_arr,
        vector<double> & out_arr
    ){
        // Convert out_arr to vector ? 
        sc.sum(in_arr, out_arr);
    });
}

Python end:

import simple
import numpy as np

sc = simple.SimpleClass()
in_arr = np.array([1.0, 2.0, 3.0])
out_arr = np.array([0.0, 0.0, 0.0])
sc.dat = 2.0

sc.sum_lambda(in_arr, out_arr)

# print(out_arr)
# array([0., 0., 0.])

Currently I workaround by creating empty vector before the sc.sum(in_arr, out_arr); call and copying out_arr element by element, followed by copy back to array_t out_arr. Is there a better way to convert it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source