C library code (in another directory)
$(CLIB)/hellolib.o: $(CLIB)/hellolib.c $(CLIB)/hellolib.h
gcc $(CLIB)/hellolib.c -g -I$(CLIB) -c -o $(CLIB)/hellolib.o
clean:
rm -f .dll .o .pyc core
force:
rm -f .dll .o .pyc core hellolib_wrap.c hellowrap.py
When run on the hellolib.i input file by this makefile, SWIG generates two files:
hellolib_wrap.c
The generated C extension module glue code file.
hellowrap.py
A Python module that imports the generated C extension module.
The former is named for the input file, and the latter per the %module directive. Really,
SWIG generates two modules today: it uses a combination of Python and C code to
achieve the integration. Scripts ultimately import the generated Python module file,
which internally imports the generated and compiled C module. You can wade through
this generated code in the book’s examples distribution if you are so inclined, but it is
prone to change over time and is too generalized to be simple.
To build the C module, the makefile runs SWIG to generate the glue code; compiles
its output; compiles the original C library code if needed; and then combines the result
with the compiled wrapper to produce _hellowrap.dll, the DLL which hellowrap.py will
expect to find when imported by a Python script:
.../PP4E/Integrate/Extend/Swig$ dir
hellolib.i makefile.hellolib-swig
.../PP4E/Integrate/Extend/Swig$ make -f makefile.hellolib-swig
/cygdrive/c/temp/swigwin-2.0.0/swig -python -I../HelloLib hellolib.i
gcc hellolib_wrap.c -g -I../HelloLib -I/usr/local/include/python3.1
-c -o hellolib_wrap.o
gcc ../HelloLib/hellolib.c -g -I../HelloLib -c -o ../HelloLib/hellolib.o
gcc -shared hellolib_wrap.o ../HelloLib/hellolib.o \
-L/usr/local/bin -lpython3.1 -o _hellowrap.dll
.../PP4E/Integrate/Extend/Swig$ dir
_hellowrap.dll hellolib_wrap.c hellowrap.py
hellolib.i hellolib_wrap.o makefile.hellolib-swig
The result is a dynamically loaded C extension module file ready to be imported by
Python code. Like all modules, _hellowrap.dll must, along with hellowrap.py, be placed
in a directory on your Python module search path (the directory where you compile
will suffice if you run Python there too). Notice that the .dll file must be built with a
leading underscore in its name; this is required because SWIG also created the .py file
of the same name without the underscore—if named the same, only one could be
1494 | Chapter 20: Python/C Integration