This interface file simply directs SWIG to read the C++ class’s type signature infor-
mation from the %-included number.h header file. SWIG uses the class declaration to
generate two different Python modules again:
number_wrap.cxx
A C++ extension module with class accessor functions
number.py
A Python shadow class module that wraps accessor functions
The former must be compiled into a binary library. The latter imports and uses the
former’s compiled form and is the file that Python scripts ultimately import. As for
simple functions, SWIG achieves the integration with a combination of Python and
C++ code.
After running SWIG, the Cygwin makefile shown in Example 20-18 combines the gen-
erated number_wrap.cxx C++ wrapper code module with the C++ class implementa-
tion file to create a _number.dll—a dynamically loaded extension module that must be
in a directory on your Python module search path when imported from a Python script,
along with the generated number.py (all files are in the same current working directory
here).
As before, the compiled C extension module must be named with a leading underscore
in SWIG today: _number.dll, following a Python convention, rather than the other
formats used by earlier releases. The shadow class module number.py internally imports
_number.dll. Be sure to use a -c++ command-line argument for SWIG; an older
-shadow argument is no longer needed to create the wrapper class in addition to the
lower-level functional interface module, as this is enabled by default.
Example 20-18. PP4E\Integrate\Extend\Swig\Shadow\makefile.number-swig
###########################################################################
Use SWIG to integrate the number.h C++ class for use in Python programs.
Update: name "_number.dll" matters, because shadow class imports _number.
Update: the "-shadow" swig command line arg is deprecated (on by default).
Update: swig no longer creates a .doc file to rm here (ancient history).
###########################################################################
PYLIB = /usr/local/bin
PYINC = /usr/local/include/python3.1
SWIG = /cygdrive/c/temp/swigwin-2.0.0/swig
all: _number.dll number.py
wrapper + real class
_number.dll: number_wrap.o number.o
g++ -shared number_wrap.o number.o -L$(PYLIB) -lpython3.1 -o $@
generated class wrapper module(s)
number_wrap.o: number_wrap.cxx number.h
g++ number_wrap.cxx -c -g -I$(PYINC)
1506 | Chapter 20: Python/C Integration