And you’re done. Well, almost; you still need to run this file through SWIG and compile
its output. As before, simply add a SWIG step to your makefile and compile its output
file into a shareable object for dynamic linking, and you’re in business. Exam-
ple 20-13 is a Cygwin makefile that does the job.
Example 20-13. PP4E\Integrate\Extend\Swig\Environ\makefile.environ-swig
build environ extension from SWIG generated code
PYLIB = /usr/local/bin
PYINC = /usr/local/include/python3.1
SWIG = /cygdrive/c/temp/swigwin-2.0.0/swig
_environ.dll: environ_wrap.c
gcc environ_wrap.c -g -I$(PYINC) -L$(PYLIB) -lpython3.1 -shared -o $@
environ_wrap.c: environ.i
$(SWIG) -python environ.i
clean:
rm -f .o .dll *.pyc core environ_wrap.c environ.py
When run on environ.i, SWIG generates two files and two modules—environ.py (the
Python interface module we import) and environ_wrap.c (the lower-level glue code
module file we compile into _environ.dll to be imported by the .py). Because the func-
tions being wrapped here live in standard linked-in C libraries, there is nothing to
combine with the generated code; this makefile simply runs SWIG and compiles the
wrapper file into a C extension module, ready to be imported:
.../PP4E/Integrate/Extend/Swig/Environ$ make -f makefile.environ-swig
/cygdrive/c/temp/swigwin-2.0.0/swig -python environ.i
gcc environ_wrap.c -g -I/usr/local/include/python3.1 -L/usr/local/bin -lpython3.1
-shared -o _environ.dll
And now you’re really done. The resulting C extension module is linked when impor-
ted, and it’s used as before (except that SWIG handled all the gory bits):
.../PP4E/Integrate/Extend/Swig/Environ$ ls
_environ.dll environ.i environ.py environ_wrap.c makefile.environ-swig
.../PP4E/Integrate/Extend/Swig/Environ$ python
>>> import environ
>>> environ.getenv('USER')
'gilligan'
>>> environ.__name__, environ.__file__, environ
('environ', 'environ.py', <module 'environ' from 'environ.py'>)
>>> dir(environ)
[ ... '_environ', 'getenv', 'putenv' ... ]
Wrapping C Environment Calls | 1501