Replies: 1 comment 1 reply
-
@hbadi Unfortunetelly it is a limitation of pybind. STL type casters create a copy of built-in containers like lists. Thus you are unable to modify them in-place on C++ side when passed via references like However, there is an approach that address this issue - #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
PYBIND11_MAKE_OPAQUE(std::vector<double>);
namespace py = pybind11;
void square1(std::vector<double> &vec) {
for (int i = 0; i < vec.size(); i++) {
vec[i] = vec[i] * vec[i];
}
}
PYBIND11_MODULE(mymodule, m) {
m.doc() = "This is the module test";
// Bind vector using pybind helper
py::bind_vector<std::vector<double> >(m, "VecDouble");
m.def("square1", &square1);
} Now it can be run in Python with additional creation of custom class (it is fairly easy to cast to a list again): In [1]: from mymodule import VecDouble, square1
In [2]: arr = VecDouble([0, 2, 4])
...: square1(arr)
In [3]: arr
Out[3]: VecDouble[0, 4, 16]
In [4]: list(arr)
Out[4]: [0.0, 4.0, 16.0] Alternatively when you use Numpy, this case is a lot easier to handle. No need for additional macros and casting: #include <pybind11/numpy.h> // Do not forget about a header!
// ...
void square1_numpy(py::array_t<double> &vec)
{
for (int i = 0; i < vec.size(); i++)
{
vec.mutable_at(i) = vec.at(i) * vec.at(i);;
}
}
// ...
m.def("square1_numpy1", &square1_numpy); Later in Python you can use it directly with an array: In [5]: import numpy as np
...: from mymodule import square1_numpy1
In [6]: arr = np.array([0, 2, 4])
...: square1_numpy1(arr)
In [7]: arr
Out[7]: array([0, 2, 4]) # What happened here?
In [8]: arr = np.array([0, 2, 4], dtype=np.float64)
...: square1_numpy1(arr)
In [9]: arr
Out[9]: array([ 0., 4., 16.]) # Works as expected! There is one catch - it wouldn't work if
At least this is to my best knowledge, hope this is enough details for a "green" answer:) Cheers! Documentation refs: |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello,
I've a very basic c++ function
Square
that takes astd::vector<double>
as reference argument and modify itfor instance :
I can't understand why either
square1
orsquare2
don't changevec
.Thanks for helping.
PS : I don't want to use
tranform
stl functionBeta Was this translation helpful? Give feedback.
All reactions