For example, when we created buttons with Python’s tkinter GUI library earlier in the
book, we called out to a C library through the extending API. When our GUI’s user
later clicked those buttons, the GUI C library caught the event and routed it to our
Python functions with embedding. Although most of the details are hidden to Python
code, control jumps often and freely between languages in such systems. Python has
an open and reentrant architecture that lets you mix languages arbitrarily.
For additional Python/C integration examples beyond this book, see the
Python source code itself; its Modules and Objects directories are a
wealth of code resources. Most of the Python built-ins we have used in
this book—from simple things such as integers and strings to more ad-
vanced tools such as files, system calls, tkinter, and DBM files—are built
with the same structures we’ll introduce here. Their utilization of inte-
gration APIs can be studied in Python’s source code distribution as
models for extensions of your own.
In addition, Python’s Extending and Embedding and Python/C API man-
uals are reasonably complete, and provide supplemental information to
the presentation here. If you plan to do integration, you should consider
browsing these as a next step. For example, the manuals go into addi-
tional details about C extension types, C extensions in threaded pro-
grams, and multiple interpreters in embedded programs, which we will
largely bypass here.
Extending Python in C: Overview
Because Python itself is coded in C today, compiled Python extensions can be coded
in any language that is C compatible in terms of call stacks and linking. That includes
C, but also C++ with appropriate “extern C” declarations (which are automatically
provided in Python header files). Regardless of the implementation language, the com-
piled Python extensions language can take two forms:
C modules
Libraries of tools that look and feel like Python module files to their clients
C types
Multiple instance objects that behave like standard built-in types and classes
Generally, C extension modules are used to implement flat function libraries, and they
wind up appearing as importable modules to Python code (hence their name). C ex-
tension types are used to code objects that generate multiple instances, carry per-
instance state information, and may optionally support expression operators just like
Python classes. C extension types can do anything that built-in types and Python-coded
classes can: method calls, addition, indexing, slicing, and so on.
To make the interface work, both C modules and types must provide a layer of “glue”
code that translates calls and data between the two languages. This layer registers
1486 | Chapter 20: Python/C Integration