pybind11

3.0.3 · active · verified Wed Apr 01

pybind11 is a lightweight, header-only library that provides seamless operability between C++11 (and newer) and Python. It's primarily used to create Python bindings for existing C++ code, minimizing boilerplate through compile-time introspection. The library is actively maintained (current version 3.0.3) with frequent bug fixes and regular major releases that often introduce ABI bumps. It supports CPython 3.8+, PyPy3 7.3.17+, and GraalPy 24.1+.

Warnings

Install

Imports

Quickstart

A minimal example demonstrating how to create a C++ function, expose it to Python using `PYBIND11_MODULE`, and then import and use the generated module from Python. The build command illustrates manual compilation on Unix-like systems, though `setuptools` or `CMake` are typically used for larger projects.

/* example.cpp */
#include <pybind11/pybind11.h>

namespace py = pybind11;

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 which adds two numbers");
}

# Python (in the same directory or after installation)
import example

result = example.add(1, 2)
print(f"The result is: {result}") # Expected: The result is: 3

# To build from source (Unix-like systems):
# Ensure C++ compiler (e.g., g++), Python dev headers, and pybind11 are available.
# c++ -O3 -Wall -shared -std=c++11 -fPIC \
#     $(python3 -m pybind11 --includes) example.cpp \
#     -o example$(python3 -m pybind11 --extension-suffix)

view raw JSON →