Post

Pybind

Install Pybind

1
2
3
4
conda create -n pybind-demo python=3.10
conda install -c conda-forge pybind11
## conda mirror
## https://mirror.tuna.tsinghua.edu.cn/help/anaconda/

Simple Example

1
2
3
4
5
6
7
8
9
10
11
#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example plugin"; // optional module docstring

    m.def("add", &add, "A function that adds two numbers");
}

Compile the c++ example code using the following command:

1
c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)

Assuming the compiled module is located in the current working directory, the following interactive Python session shows how to load and execute the example:

1
2
3
4
5
6
7
python
Python 3.10.15 (main, Oct  3 2024, 07:27:34) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> example.add(1, 2)
3
>>>

To find out more, please consult the references.

References

This post is licensed under CC BY 4.0 by the author.