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+.
pip install pybind11Verified import paths — ran on the pinned version, not inferred.
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.
Rebuild all pybind11-based extensions with pybind11 v3.0.0 or later to ensure compatibility across modules.
Ensure your build environment uses Python 3.8+ (or supported PyPy/GraalPy versions) and CMake 3.15+ when upgrading to pybind11 v3.0.0+.
Switch to using `Python_*` variables in your `CMakeLists.txt` for Python detection instead of `PYTHON_*`. Refer to the pybind11 upgrade guide.
Migrate to `py::native_enum` for improved integration with Python's `enum` system. While `py::enum_` is still present, it may be removed in a future 3.x release.
Consult the pybind11 documentation on GIL management, use `py::gil_scoped_acquire` or `py::gil_scoped_release` as needed, and consider lazy initialization for global pybind11 objects.
Design your C++ modules to be stateless or carefully manage state per interpreter. Initialization functions (`PYBIND11_MODULE`) will run for each interpreter.
Always use `py::cast<TargetType>(py_object_ptr)` with the explicit template argument for safe conversion.
Ensure that the Python interpreter is running a valid Python script. If C++ code needs to be tested, it must be properly compiled, linked, and then imported/called from a Python script.