CHAPTER 20
Python/C Integration
“I Am Lost at C”
Throughout this book, our programs have all been written in Python code. We have
used interfaces to services outside Python, and we’ve coded reusable tools in the Python
language, but all our work has been done in Python itself. Despite our programs’ scale
and utility, they’ve been Python through and through.
For many programmers and scripters, this mode makes perfect sense. In fact, such
standalone programming is one of the main ways people apply Python. As we’ve seen,
Python comes with batteries included—interfaces to system tools, Internet protocols,
GUIs, data storage, and much more is already available. Moreover, most custom tasks
we’re likely to encounter have prebuilt solutions in the open source world; the PIL
system, for example, allows us to process images in tkinter GUIs by simply running a
self-installer.
But for some systems, Python’s ability to integrate with components written in (or
compatible with) the C programming language is a crucial feature. In fact, Python’s
role as an extension and interface language in larger systems is one of the reasons for
its popularity and why it is often called a “scripting” language in the first place. Its
design supports hybrid systems that mix components written in a variety of program-
ming languages. Because different languages have different strengths, being able to pick
and choose on a component-by-component basis is a powerful concept. You can add
Python to the mix anywhere you need a flexible and comparatively easy-to-use language
tool, without sacrificing raw speed where it matters.
Compiled languages such as C and C++ are optimized for speed of execution, but are
complex to program—for developers, and especially for end users who need to tailor
programs. Because Python is optimized for speed of development, using Python scripts
to control or customize software components written in C or C++ can yield more
flexible systems, quicker execution, and faster development modes. For example, mov-
ing selected components of a pure Python program to C can optimize program per-
formance. Moreover, systems designed to delegate customizations to Python code
1483