This is a Cygwin makefile that uses gcc to compile our C code on Windows; other
platforms are analogous but will vary. As we learned in Chapter 5, Cygwin provides a
Unix-like environment and libraries on Windows. To work along with the examples
here, either install Cygwin on your Windows platform, or change the makefiles listed
per your compiler and platform requirements. Be sure to include the path to Python’s
install directory with -I flags to access Python include (a.k.a. header) files, as well as
the path to the Python binary library file with -L flags, if needed; mine point to
Python 3.1’s location on my laptop after building it from its source. Also note that you’ll
need tabs for the indentation in makefile rules if a cut-and-paste from an ebook sub-
stituted or dropped spaces.
Now, to use the makefile in Example 20-2 to build the extension module in Exam-
ple 20-1, simply type a standard make command at your shell (the Cygwin shell is used
here, and I add a line break for clarity):
.../PP4E/Integrate/Extend/Hello$ make -f makefile.hello
gcc hello.c -g -I/usr/local/include/python3.1 -shared
-L/usr/local/bin -lpython3.1 -o hello.dll
This generates a shareable object file—a .dll under Cygwin on Windows. When com-
piled this way, Python automatically loads and links the C module when it is first
imported by a Python script. At import time, the .dll binary library file will be located
in a directory on the Python import search path, just like a .py file. Because Python
always searches the current working directory on imports, this chapter’s examples will
run from the directory you compile them in (.) without any file copies or moves. In
larger systems, you will generally place compiled extensions in a directory listed in
PYTHONPATH or .pth files instead, or use Python’s distutils to install them in the site-
packages subdirectory of the standard library.
Finally, to call the C function from a Python program, simply import the module
hello and call its hello.message function with a string; you’ll get back a normal Python
string:
.../PP4E/Integrate/Extend/Hello$ python
>>> import hello # import a C module
>>> hello.message('world') # call a C function
'Hello, world'
>>> hello.message('extending')
'Hello, extending'
And that’s it—you’ve just called an integrated C module’s function from Python. The
most important thing to notice here is that the C function looks exactly as if it were
coded in Python. Python callers send and receive normal string objects from the call;
the Python interpreter handles routing calls to the C function, and the C function itself
handles Python/C data conversion chores.
In fact, there is little to distinguish hello as a C extension module at all, apart from its
filename. Python code imports the module and fetches its attributes as if it had been
written in Python. C extension modules even respond to dir calls as usual and have the
A Simple C Extension Module| 1489