With pybind11
, which can integrate Python and C ++,
You can pass a list from Python to a C ++ function via the STL container.
[External link: How to execute C ++ code from Python using pybind11](https://myenigma.hatenablog.com/entry/2016/12/17/075812#STL%E3%81%AE%E3%82% B3% E3% 83% B3% E3% 83% 86% E3% 83% 8A% E3% 81% AE% E3% 82% 84% E3% 82% 8A% E5% 8F% 96% E3% 82% 8A)
However, this is passed by value, so you need to return it on the C ++ side to use the updated list in Python.
On the other hand, when using existing C ++ assets, I do not want to modify the C ++ source code as much as possible, so You may not want to set a new return value or rewrite the update.
So by going through Numpy instead of a list Although the usage is limited, it can be passed by reference, so it will be shared.
Basically, I think it is better to use mutable_data
and ʻEigen` explained in the link below.
Other than that, there is a content like this.
Introduction to external link pybind11 (3) NumPy cooperation part 1
Introduction to external link pybind11 (3) NumPy cooperation part 2
--I will not explain how to install pybind and how to use it basically. --Pybind and C ++ have little knowledge, so please comment if you make a mistake.
Define a function ʻupdate1 () that passes a list via an STL container and a function ʻupdate2 ()
that you pass in Numpy.
Both try to update the value of the received array to 1.0.
hoge.cpp
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <vector>
namespace py = pybind11;
void update1(std::vector<double> &x)
{
int i;
for(i = 0; i < 3; i ++)
{
x[i] = 1.0;
}
}
void update2(py::array_t<double> x)
{
auto x_buf = x.request();
double *x_ptr = (double *)x_buf.ptr;
int i;
for(i = 0; i < 3; i ++)
{
x_ptr[i] = 1.0;
}
}
PYBIND11_MODULE(hoge, m)
{
m.doc() = "hoge module";
m.def("update1", &update1, "update1 function");
m.def("update2", &update2, "update2 function");
}
Pass the list [1., 2., 3.]
to ʻupdate1, ʻupdate2
,
A script that verifies how the list changes after applying each function.
test.py
import numpy as np
import hoge
x = [1., 2., 3.]
print(x)
hoge.update1(x)
print(x)
x = np.array(x)
hoge.update2(x)
print(x)
[1.0, 2.0, 3.0]
[1.0, 2.0, 3.0]
[1. 1. 1.]
You can see that the value is not updated with ʻupdate1 and is updated with ʻupdate2
.
As explained in the reference link, if the type (double this time) does not match on the Python side and the C ++ side Please note that it will be passed by value.
Recommended Posts