C-based implementation of Python) code, without requiring alternative byte code
compilers.
Moreover, the f2py and PyFort systems provide integration with FORTRAN code,
and other tools provide access to languages such as Delphi and Objective-C.
Among these, the PyObjC project aims to provide a bridge between Python and
Objective-C; this supports writing Cocoa GUI applications on Mac OS X in Python.
Search the Web for details on other language integration tools. Also look for a wiki
page currently at http://www.python.org that lists a large number of other integrat-
able languages, including Prolog, Lisp, TCL, and more.
Because many of these systems support bidirectional control flows—both extending
and embedding—we’ll return to this category at the end of this chapter in the context
of integration at large. First, though, we need to shift our perspective 180 degrees to
explore the other mode of Python/C integration: embedding.
Mixing Python and C++
Python’s standard implementation is currently coded in C, so all the normal rules about
mixing C programs with C++ programs apply to the Python interpreter. In fact, there
is nothing special about Python in this context, but here are a few pointers.
When embedding Python in a C++ program, there are no special rules to follow. Simply
link in the Python library and call its functions from C++. Python’s header files auto-
matically wrap themselves in extern "C" {...} declarations to suppress C++ name
mangling. Hence, the Python library looks like any other C component to C++; there
is no need to recompile Python itself with a C++ compiler.
When extending Python with C++ components, Python header files are still C++
friendly, so Python API calls in C++ extensions work like any other C++-to-C call. But
be sure to wrap the parts of your extension code made visible to Python with extern
"C" declarations so that they can be called by Python’s C code. For example, to wrap
a C++ class, SWIG generates a C++ extension module that declares its initialization
function this way.
Embedding Python in C: Overview
So far in this chapter, we’ve explored only half of the Python/C integration picture:
calling C services from Python. This mode is perhaps the most commonly deployed; it
allows programmers to speed up operations by moving them to C and to utilize external
libraries by wrapping them in C extension modules and types. But the inverse can be
just as useful: calling Python from C. By delegating selected components of an appli-
cation to embedded Python code, we can open them up to onsite changes without
having to ship or rebuild a system’s full code base.
This section tells this other half of the Python/C integration tale. It introduces the
Python C interfaces that make it possible for programs written in C-compatible
1514 | Chapter 20: Python/C Integration