Let’s see how bindings work before going into C++ binding tools
This is how CPython itself is implemented (and PyPy supports this too)
C reminder:
staticmeans visible in this file only
import sysFirst, here’s the code we want to wrap:
%%writefile pysimple.c
#include <Python.h>
float square(float x) {
return x*x;
}Writing pysimple.c
Okay, now we need to manually build the Python -> C -> Python conversion. All Python objects, regardless of type, are PyObject*. All the necessary conversions are provided using Py* functions.
PyArg_ParseTuple(PyObject*, format, *result)will parse a tuple into C types.PyFloat_FromDouble(double)will convert a C item into aPyObject*.
%%writefile -a pysimple.c
static PyObject* square_wrapper(PyObject* self, PyObject* args) {
float input, result;
if (!PyArg_ParseTuple(args, "f", &input)) {
return NULL;
}
result = square(input);
return PyFloat_FromDouble(result);
}Appending to pysimple.c
Next, we need a PyMethodDef. This is a structure that holds functions. The structure is “name”, wrapper function, argument type, and doc string. Since C doesn’t know when an array ends, you use a null terminated row at the end to signal that you are done. The argument type is an item from this list. METH_FASTCALL (3.7+) is the fastest choice for functions with several arguments.
Looking back, this could have been a little simpler with METH_O, which takes exactly one argument and therefore you’d avoid the Tuple.
%%writefile -a pysimple.c
static PyMethodDef pysimple_methods[] = {
{ "square", square_wrapper, METH_VARARGS, "Square function" },
{ NULL, NULL, 0, NULL }
};Appending to pysimple.c
Now we need a module structure. I won’t go into it in great detail; PyModuleDef_HEAD_INIT is always there. Then the name of the module, then the module docstring (or NULL), then a size for subinterpreters (-1 to disable), the methods you defined above.
%%writefile -a pysimple.c
static struct PyModuleDef pysimple_module = {
PyModuleDef_HEAD_INIT, "pysimple", NULL, -1, pysimple_methods
};Appending to pysimple.c
Finally we have the last bit; you need to define a symbol with a specific name, PyInit_<name>, where <name> is the name of the module.
%%writefile -a pysimple.c
PyMODINIT_FUNC PyInit_pysimple(void) {
return PyModule_Create(&pysimple_module);
}Appending to pysimple.c
To compile our module, we need to use a build system of some sort. This is the correct way to compile it, and cross platform. You can just compile it by hand, which I’ve done here in the past, but it’s very hard to get it right, and very system specific. I’m going to use CMake for this example. python_add_library adds the flags a Python module needs, and WITH_SOABI adds the Python-specific suffix to the file name.
%%writefile CMakeLists.txt
cmake_minimum_required(VERSION 3.26...4.4)
project(pysimple LANGUAGES C)
find_package(Python REQUIRED COMPONENTS Interpreter Development.Module)
python_add_library(pysimple MODULE pysimple.c WITH_SOABI)
# Put the module next to the notebook so we can import it
set_target_properties(pysimple PROPERTIES
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")Writing CMakeLists.txt
For simplicity, I’m going to run CMake directly and put the module in the source directory. In a real package, a build backend like scikit-build-core runs CMake for you. We’ll show that soon.
!cmake -GNinja -S . -B build -DPython_EXECUTABLE={sys.executable}
!cmake --build build-- The C compiler identification is GNU 15.2.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Found Python: /home/runner/work/se-for-sci.github.io/se-for-sci.github.io/.pixi/envs/default/bin/python (found version "3.13.18") found components: Interpreter Development.Module
-- Configuring done (0.4s)
-- Generating done (0.0s)
-- Build files have been written to: /home/runner/work/se-for-sci.github.io/se-for-sci.github.io/content/week09_binding/02-cpython/build
[0/2] Building C object CMakeFiles/pysimple.dir/pysimple.c.o[2/2] Linking C shared module /home/ru...ysimple.cpython-313-x86_64-linux-gnu.so
Run:¶
import pysimple
pysimple.square(2.0)4.0pysimple.square(1)1.0pysimple.__file__'/home/runner/work/se-for-sci.github.io/se-for-sci.github.io/content/week09_binding/02-cpython/pysimple.cpython-313-x86_64-linux-gnu.so'Python limited API: PEP 384¶
One possible benefit of building your own Python extensions this way is that you can use the Python limited API. This defines a reduced subset of functionality that you must stick to, but in return, you now can use a single compiled extension with multiple versions of Python, from a minimum (3.2 or later) to the current version (and future versions!). PEP 803 adds abi3t, a stable ABI that works with both free-threaded and regular builds of Python 3.15+.
PyBuffer protocol support was not part of the limited API until Python 3.11.
Support:
nanobind (a lightweight set of the core pybind11 functionality for C++17+ and Python 3.9+) supports the limited API for Python 3.12+.
pybind11 support is in progress (pybind11#6198).
Rust via PyO3 supports it with the
abi3-py3Xfeatures, and maturin tags the wheels.Cython 3.1+ supports it. abi3t is not supported yet.
SWIG 4.2+ supports it, but not with
-builtin.
To use:
Define
Py_LIMITED_APIto the minimum Python version you want to support. For example,0x030B0000is 3.11 (0x03020000, or 3.2, is the earliest). You can put a#defineabove thePython.hinclude, or let the build system set it.Tell the build system to make a stable ABI module. In CMake 3.26+, find the
Development.SABIModulecomponent instead ofDevelopment.Module, and addUSE_SABI 3.11topython_add_library. This also definesPy_LIMITED_APIfor you. scikit-build-core, meson-python, and setuptools have similar settings.Make sure you don’t use any of the (now missing)
Py*functions that are not part of the limited API.
Exercise¶
Try to convert the above code to use the Python limited API by making the two CMake changes. How did the file name change? What did you have to do to get it to load the new file? (note: you also need to delete the version-specific cpython-3XX file)