Embedding typically takes the role of customization—by running user-configurable
Python code, a system can be modified without shipping or building its full source
code. For instance, some programs provide a Python customization layer that can be
used to modify the program on site by modifying Python code. Embedding is also
sometimes used to route events to Python-coded callback handlers. Python GUI tool-
kits, for example, usually employ embedding in some fashion to dispatch user events.
Figure 20-1 sketches this traditional dual-mode integration model. In extending, con-
trol passes from Python through a glue layer on its way to C code. In embedding, C
code processes Python objects and runs Python code by calling Python C API functions.
Because Python is “on top” in extending, it defines a fixed integration structure, which
can be automated with tools such as SWIG—a code generator we’ll meet in this chapter,
which produces glue code required to wrap C and C++ libraries. Because Python is
subordinate in embedding, it instead provides a set of API tools which C programs
employ as needed.
Figure 20-1. Traditional integration model
In some models, things are not as clear-cut. For example, under the ctypes module
discussed later, Python scripts make library calls rather than employing C glue code.
In systems such as Cython (and its Pyrex predecessor), things are more different still—
C libraries are produced from combinations of Python and C code. And in Jython and
IronPython, the model is similar, but Java and C# components replace the C language,
and the integration is largely automated. We will meet such alternative systems later
in this chapter. For now, our focus is on traditional Python/C integration models.
This chapter introduces extending first, and then moves on to explore the basics of
embedding. Although we will study these topics in isolation, keep in mind that many
systems combine the two techniques. For instance, embedded Python code run from
C can also import and call linked-in C extensions to interface with the enclosing ap-
plication. And in callback-based systems, C libraries initially accessed through extend-
ing interfaces may later use embedding techniques to run Python callback handlers
on events.
“I Am Lost at C” | 1485