[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

This file spells out the C function’s type signature. In general, SWIG scans files con-
taining ANSI C and C++ declarations. Its input file can take the form of an interface
description file (usually with a .i suffix) or a C/C++ header or source file. Interface files
like this one are the most common input form; they can contain comments in C or
C++ format, type declarations just like standard header files, and SWIG directives that
all start with %. For example:


%module
Sets the module’s name as known to Python importers.


%{...%}
Encloses code added to generated wrapper file verbatim.


extern statements
Declare exports in normal ANSI C/C++ syntax.


%include
Makes SWIG scan another file (-I flags give search paths).


In this example, SWIG could also be made to read the hellolib.h header file of Exam-
ple 20-5 directly. But one of the advantages of writing special SWIG input files like
hellolib.i is that you can pick and choose which functions are wrapped and exported
to Python, and you may use directives to gain more control over the generation process.


SWIG is a utility program that you run from your build scripts; it is not a programming
language, so there is not much more to show here. Simply add a step to your makefile
that runs SWIG and compile its output to be linked with Python. Example 20-7 shows
one way to do it on Cygwin.


Example 20-7. PP4E\Integrate\Extend\Swig\makefile.hellolib-swig


##################################################################


Use SWIG to integrate hellolib.c for use in Python programs on


Cygwin. The DLL must have a leading "_" in its name in current


SWIG (>1.3.13) because also makes a .py without "_" in its name.


##################################################################


PYLIB = /usr/local/bin
PYINC = /usr/local/include/python3.1
CLIB = ../HelloLib
SWIG = /cygdrive/c/temp/swigwin-2.0.0/swig


the library plus its wrapper


_hellowrap.dll: hellolib_wrap.o $(CLIB)/hellolib.o
gcc -shared hellolib_wrap.o $(CLIB)/hellolib.o \
-L$(PYLIB) -lpython3.1 -o $@


generated wrapper module code


hellolib_wrap.o: hellolib_wrap.c $(CLIB)/hellolib.h
gcc hellolib_wrap.c -g -I$(CLIB) -I$(PYINC) -c -o $@


hellolib_wrap.c: hellolib.i
$(SWIG) -python -I$(CLIB) hellolib.i


The SWIG Integration Code Generator | 1493
Free download pdf