A first binding#
Every program in the C++ module ran on its own, started
from the terminal through its main. The home page’s script instead
imports the engine into Python and calls it. This chapter builds the
smallest such bridge: it takes the C++ function
lj_energy(r, epsilon, sigma) from Functions,
makes it callable from Python with four extra lines of C++, and follows one
call across.
What Python can import#
Python imports two kinds of module. A .py file is Python source, read and
run by Python itself. An extension module is a compiled library: machine
code, built by a C or C++ compiler, that Python loads like any other module.
The Python documentation describes it as
a shared library that exports an initialization function:
when Python imports the module for the first time, it calls that function,
and the function sets up the module’s contents. The file must be named after
the module plus a suffix that depends on the Python version and the system,
such as .cpython-312-darwin.so for Python 3.12 on a Mac
(defining extension modules).
Writing that initialization function by hand takes a lot of code. pybind11 writes it for you.
The binding#
1#include <cmath>
2#include <pybind11/pybind11.h>
3
4double lj_energy(double r, double epsilon, double sigma) {
5 double sr6 = std::pow(sigma / r, 6);
6 return 4.0 * epsilon * (sr6 * sr6 - sr6);
7}
8
9PYBIND11_MODULE(ljmodule, m) {
10 m.doc() = "The Lennard-Jones pair energy, written in C++";
11 m.def("lj_energy", &lj_energy, "LJ energy of one pair at distance r");
12}
Lines 4–7 are the function from the C++ module, unchanged. The new lines:
Line 2 includes pybind11’s header.
Line 9,
PYBIND11_MODULE(ljmodule, m), creates the function that Python calls when it imports the module (pybind11 first steps). The first argument is the module’s name, written without quotes; the second,m, is the module being built.Line 10 sets the module’s description.
Line 11,
m.def(...), adds a Python function namedlj_energythat runs the C++ function&lj_energy(the&takes the function’s address, as it took a variable’s address in chapter 1 of the C++ module). The last argument is the function’s description for Python’shelp().
Build and import#
pybind11 itself is a header-only library: compiling with its headers is all it takes, with no extra library to link (building manually). Install it into the Python you will import the module with; the examples here use pybind11 2.13.1, the same version the engine’s build fetches:
$ python3 -m pip install "pybind11==2.13.1"
The build is one compiler command, the one from pybind11’s documentation for version 2.13 on macOS:
$ c++ -O3 -Wall -shared -std=c++17 -undefined dynamic_lookup \
$(python3 -m pybind11 --includes) ljmodule.cpp \
-o ljmodule$(python3-config --extension-suffix)
Each part:
-sharedbuilds a shared library instead of a program: there is nomain, and the result is loaded by another program, here Python.$(python3 -m pybind11 --includes)runs a small command and pastes its output into the line: the folders that hold pybind11’s and Python’s headers.-o ljmodule$(python3-config --extension-suffix)names the output after the module, plus the suffix this Python expects:ljmodule.cpython-312-darwin.so.-undefined dynamic_lookupis for macOS only: it lets the library refer to Python’s own functions, which are found when Python loads it. On Linux, leave it out.
The result is a compiled library, and it exports the initialization function
that PYBIND11_MODULE wrote, named PyInit_ plus the module name:
$ file ljmodule.cpython-312-darwin.so
ljmodule.cpython-312-darwin.so: Mach-O 64-bit dynamically linked shared library arm64
$ nm -gU ljmodule.cpython-312-darwin.so | grep PyInit
00000000000007c0 T _PyInit_ljmodule
Python, run in the same folder, now imports it like any module:
import ljmodule
print(ljmodule.lj_energy(1.5, 1.0, 1.0))
print(ljmodule.lj_energy(1.5, 2.0, 1.0))
print(ljmodule.lj_energy(1.5, 1.0, 1.2))
$ python3 use_it.py
-0.3203365942785746
-0.6406731885571492
-0.7736980930559998
These are the three values of parameters.cpp in the
Functions chapter, printed with
more digits: std::cout shows six significant digits, Python shows enough
digits to identify the number exactly. They are the same numbers. Printed
with 17 digits, the C++ result for the first call is
-0.32033659427857458, and Python confirms that this equals
-0.3203365942785746.
One call, step by step#
The C++ function takes doubles; Python passes Python floats. pybind11
stands between them (Fig. 20):
Python calls the function that
m.defmade.pybind11 converts each argument to the type the C++ function expects: each Python
floatbecomes a C++double. A Pythonintis also accepted, because it can be converted to a floating-point number (functions).The C++ function runs, as compiled machine code.
pybind11 converts the returned
doubleback into a Pythonfloat.
Fig. 20 One call of ljmodule.lj_energy. pybind11 converts the arguments on the way
in and the result on the way out; the C++ function never sees a Python
object.#
If an argument cannot be converted, pybind11 refuses the call before any C++
runs, and Python raises a TypeError that lists the types it accepts:
>>> ljmodule.lj_energy("far", 1.0, 1.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: lj_energy(): incompatible function arguments. The following argument types are supported:
1. (arg0: float, arg1: float, arg2: float) -> float
Invoked with: 'far', 1.0, 1.0
This is the same mistake as storing text in a double in
A first program. There the
compiler caught it before the program existed; here the call is made from
Python, whose types are known only when the line runs, so the check happens
at that moment.
Names and default values#
The error message calls the parameters arg0, arg1, arg2: pybind11 does
not know their names. py::arg tells it, and = 1.0 gives a default value
(keyword arguments).
A second module, ljnamed, differs from ljmodule only in these lines:
namespace py = pybind11;
PYBIND11_MODULE(ljnamed, m) {
m.doc() = "The Lennard-Jones pair energy, written in C++";
m.def("lj_energy", &lj_energy, "LJ energy of one pair at distance r",
py::arg("r"), py::arg("epsilon") = 1.0, py::arg("sigma") = 1.0);
}
namespace py = pybind11; lets the code write py::arg instead of
pybind11::arg. Built with the same command, the function now has names and
defaults that Python can use:
>>> import ljnamed
>>> print(ljnamed.lj_energy.__doc__)
lj_energy(r: float, epsilon: float = 1.0, sigma: float = 1.0) -> float
LJ energy of one pair at distance r
>>> ljnamed.lj_energy(1.5)
-0.3203365942785746
>>> ljnamed.lj_energy(1.5, sigma=1.2)
-0.7736980930559998
If you know Python
The Functions chapter noted that C++ has no named
arguments. The C++ function still has none: py::arg gives names to the
Python side of the bridge only, and pybind11 matches them to positions before
calling C++.
Check yourself#
1. You edit lj_energy in ljmodule.cpp and run use_it.py again without rebuilding. Which version runs?
The old one. Python loads the compiled .so file, and the .so changes only
when you run the compiler command again, just as ./pair in the C++ module
runs the last compiled program.
2. What does ljmodule.lj_energy(2, 1, 1) return, and why is an int accepted?
-0.0615234375. pybind11 converts each Python int to a C++ double,
because an integer can be turned into a floating-point number.
3. You build the module with -o ljmodule.so, without the suffix. Can Python 3.12 on this Mac import it?
Yes: Python’s list of extension suffixes also includes the plain .so. But
the suffix records which Python the file was built for, so ljmodule.cpython-312-darwin.so
is the safer name: a different Python version will not mistake it for its own.
4. Why does ljmodule.lj_energy(“far”, 1.0, 1.0) fail with a TypeError instead of a compile error?
The call is in Python, and Python checks types when the line runs. pybind11
tries to convert "far" to a double, cannot, and raises the error before
the C++ function is called.
Next#
ljmodule makes one function callable. The engine’s bridge does the same
thing on a larger scale: whole classes instead of one function, and C++
objects that Python and C++ use at the same time.
Binding the engine reads it, and follows the
home page’s sim.run() across it.