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

(yzsuai) #1

number_wrap.cxx: number.i
$(SWIG) -c++ -python number.i


number.py: number.i
$(SWIG) -c++ -python number.i


wrapped C++ class code


number.o: number.cxx number.h
g++ number.cxx -c -g -Wno-deprecated


non Python test


cxxtest:
g++ main.cxx number.cxx -Wno-deprecated


clean:
rm -f .pyc .o .dll core a.exe
force:
rm -f
.pyc .o .dll core a.exe number_wrap.cxx number.py


As usual, run this makefile to generate and compile the necessary glue code into an
extension module that can be imported by Python programs:


.../PP4E/Integrate/Extend/Swig/Shadow$ make -f makefile.number-swig
/cygdrive/c/temp/swigwin-2.0.0/swig -c++ -python number.i
g++ number_wrap.cxx -c -g -I/usr/local/include/python3.1
g++ number.cxx -c -g -Wno-deprecated
g++ -shared number_wrap.o number.o -L/usr/local/bin -lpython3.1 -o _number.dll

.../PP4E/Integrate/Extend/Swig/Shadow$ ls
_number.dll makefile.number-swig number.i number_wrap.cxx
a.exe number.cxx number.o number_wrap.o
main.cxx number.h number.py

Using the C++ Class in Python


Once the glue code is generated and compiled, Python scripts can access the C++ class
as though it were coded in Python. In fact, it is—the imported number.py shadow class
which runs on top of the extension module is generated Python code. Example 20-19
repeats the main.cxx file’s class tests. Here, though, the C++ class is being utilized from
the Python programming language—an arguably amazing feat, but the code is remark-
ably natural on the Python side of the fence.


Example 20-19. PP4E\Integrate\Extend\Swig\Shadow\main.py


"""
use C++ class in Python code (c++ module + py shadow class)
this script runs the same tests as the main.cxx C++ file
"""


from number import Number # imports .py C++ shadow class module


num = Number(1) # make a C++ class object in Python
num.add(4) # call its methods from Python


Wrapping C++ Classes with SWIG | 1507
Free download pdf