How do I call C++ from Python (pybind11)?

Pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, primarily aimed at creating Python bindings for C++ code. It allows seamless integration of C++ with Python, which is particularly useful for computational tasks that require performance optimization. This guide will demonstrate how to call C++ code from Python using Pybind11.

Example Code

# Include pybind11 headers
#include <pybind11/pybind11.h>

// A simple C++ function
int add(int a, int b) {
    return a + b;
}

// Create a Python module
PYBIND11_MODULE(example, m) {
    m.def("add", &add, "A function that adds two numbers");
}

To compile the C++ code into a Python module, you would typically use a setup script as follows:

from setuptools import setup, Extension
import pybind11

module = Extension('example', sources=['example.cpp'], include_dirs=[pybind11.get_include()])

setup(
    name='example',
    ext_modules=[module],
)

Building the module can be done using the following command:

python setup.py build_ext --inplace

Once built, you can use the module in Python like this:

import example
result = example.add(1, 2)
print(result)  # Output: 3

Pybind11 C++ integration with Python Python bindings C++ modules performance optimization C++ in Python