Calling Python from C++ via pybind11
Wrap C++ code as a Python module using pybind11.
Why pybind11?
pybind11 is a header-only library that creates Python bindings for C++ code with minimal boilerplate. Used by SciPy, TensorFlow, and many other projects.
A Minimal Module
Define a Python module in a single file with the PYBIND11_MODULE macro.
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add(int a, int b) { return a + b; }
PYBIND11_MODULE(mymodule, m) {
m.def("add", &add, "Add two integers");
}All lessons in this course
- Extern C and the C ABI
- Calling Python from C++ via pybind11
- C++ for Rust FFI Boundaries
- Using SWIG for Multi-Language Bindings