Pass a list by reference from Python to C ++ with pybind11

Introduction

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

important point

--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.

C ++ code

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");
}

Python code

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)

result

[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

Pass a list by reference from Python to C ++ with pybind11
Read line by line from a file with Python
Try embedding Python in a C ++ program with pybind11
From buying a computer to running a program with python
[Python] How to call a c function from python (ctypes)
Embed a Python interpreter into a C ++ app with pybind11 + cmake
[Python] How to make a list of character strings character by character
Pass OpenCV data from the original C ++ library to Python
Extract the value closest to a value from a Python list element
Solve ABC163 A ~ C with Python
Call C from Python with DragonFFI
Create folders from '01' to '12' with python
python / Make a dict from a list.
Solve ABC168 A ~ C with Python
Solve ABC162 A ~ C with Python
Solve ABC167 A ~ C with Python
Solve ABC158 A ~ C with Python
I tried to make a generator that generates a C # container class from CSV with Python
Try to extract a character string from an image with Python3
[Python] A memo to operate ROM created by GBDK with PyBoy
I tried to create a list of prime numbers with python
How to remove duplicates from a Python list while preserving order.
[Python] How to convert a 2D list to a 1D list
Send a message from Python to Slack
I tried to communicate with a remote server by Socket communication with Python.
Create a tool to automatically furigana with html using Mecab from Python3
When running a Python shell from Electron, pass multiple arguments to run Python.
[Introduction to Python] How to sort the contents of a list efficiently with list sort
Extension of Python by C or C ++ (when there are multiple arguments, when passing a list from the Python side)
Build an environment to execute C ++ functions from Python with Pybind11 (for Windows & Visual Studio Code people)
Send a message from Slack to a Python server
[Python] List Comprehension Various ways to create a list
Run a Python script from a C # GUI application
[python] How to display list elements side by side
Edit Excel from Python to create a PivotTable
How to read a CSV file with Python 2/3
Send a message to LINE with Python (LINE Notify)
How to open a web browser from python
Create a C array from a Python> Excel sheet
Try to draw a life curve with python
I want to make a game with Python
How to generate a Python object from JSON
Try to make a "cryptanalysis" cipher with Python
Decide to assign a laboratory with Python (fiction)
Steps to create a Twitter bot with python
Create a decision tree from 0 with Python (1. Overview)
Call a Python script from Embedded Python in C ++ / C ++
Try to make a dihedral group with Python
A simple to-do list created with Python + Django
A python amateur tries to summarize the list ②
Wrap C ++ with Cython for use from Python
Challenge AtCoder (ABC) 164 with Python! A ~ C problem
From Python environment construction to virtual environment construction with anaconda
I want to write to a file with Python
A layman wants to get started with Python
Convert strings to character-by-character list format with python
Extract data from a web page with Python
How to pass the execution result of a shell command in a list in Python
Try to beautify with Talking Head Anime from a Single Image [python preparation]
Get a list of articles posted by users with Python 3 Qiita API v2
WEB scraping with python and try to make a word cloud from reviews