[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

don’t need to be shipped with full source code and don’t require end users to learn
complex or proprietary languages.


In this last technical chapter of this book, we’re going to take a brief look at tools for
interfacing with C-language components, and discuss both Python’s ability to be used
as an embedded language tool in other systems, and its interfaces for extending Python
scripts with new modules implemented in C-compatible languages. We’ll also briefly
explore other integration techniques that are less C specific, such as Jython.


Notice that I said “brief” in the preceding paragraph. Because not all Python program-
mers need to master this topic, because it requires studying C language code and
makefiles, and because this is the final chapter of an already in-depth book, this chapter
omits details that are readily available in both Python’s standard manual set, and the
source code of Python itself. Instead, here we’ll take a quick look at a handful of basic
examples to help get you started in this domain, and hint at the possibilities they imply
for Python systems.


Extending and Embedding


Before we get to any code, I want to start out by defining what we mean by “integration”
here. Although that term can be interpreted almost as widely as “object,” our focus in
this chapter is on tight integration—where control is transferred between languages by
a simple, direct, and fast in-process function call. Although it is also possible to link
components of an application less directly using IPC and networking tools such as
sockets and pipes that we explored earlier in the book, we are interested in this part of
the book in more direct and efficient techniques.


When you mix Python with components written in C (or other compiled languages),
either Python or C can be “on top.” Because of that, there are two distinct integration
modes and two distinct APIs:


The extending interface
For running compiled C library code from Python programs


The embedding interface
For running Python code from compiled C programs


Extending generally has three main roles: to optimize programs—recoding parts of a
program in C is a last-resort performance boost; to leverage existing libraries—opening
them up for use in Python code extends their reach; and to allow Python programs to
do things not directly supported by the language—Python code cannot normally access
devices at absolute memory addresses, for instance, but can call C functions that do.
For example, the NumPy package for Python is largely an instance of extending at work:
by integrating optimized numeric libraries, it turns Python into a flexible and efficient
system for numeric programming that some compare to Matlab.


1484 | Chapter 20: Python/C Integration

Free download pdf