# to build: python disthello.py build
# resulting dll shows up in build subdir
from distutils.core import setup, Extension
setup(ext_modules=[Extension('hello', ['hello.c'])])
This is a Python script that specifies compilation of the C extension using tools in the
distutils package—a standard part of Python that is used to build, install, and dis-
tribute Python extensions coded in Python or C. distutil’s larger goal is automated
and portable builds and installs for distributed packages, but it also knows how to build
C extensions portably. Systems generally include a setup.py which installs in site-
packages of the standard library. Regrettably, distutils is also too large to have survived
the cleaver applied to this chapter’s material; see its two manuals in Python’s manuals
set for more details.
The SWIG Integration Code Generator
As you can probably tell, manual coding of C extensions can become fairly involved
(this is almost inevitable in C language work). I’ve introduced the basics in this chapter
thus far so that you understand the underlying structure. But today, C extensions are
usually better and more easily implemented with a tool that generates all the required
integration glue code automatically. There are a variety of such tools for use in the
Python world, including SIP, SWIG, and Boost.Python; we’ll explore alternatives at the
end of this chapter. Among these, the SWIG system is widely used by Python
developers.
SWIG—the Simplified Wrapper and Interface Generator, is an open source system
created by Dave Beazley and now developed by its community, much like Python. It
uses C and C++ type declarations to generate complete C extension modules that in-
tegrate existing libraries for use in Python scripts. The generated C (and C++) extension
modules are complete: they automatically handle data conversion, error protocols,
reference-count management, and more.
That is, SWIG is a program that automatically generates all the glue code needed to
plug C and C++ components into Python programs; simply run SWIG, compile its
output, and your extension work is done. You still have to manage compilation and
linking details, but the rest of the C extension task is largely performed by SWIG.
A Simple SWIG Example
To use SWIG, instead of writing the C code in the prior section, write the C function
you want to use from Python without any Python integration logic at all, as though it
is to be used from C alone. For instance, Example 20-4 is a recoding of Example 20-1
as a straight C function.
The SWIG Integration Code Generator | 1491