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

(yzsuai) #1
>>> x, y
(<number.Number; proxy of <Swig Object of type 'Number *' at 0x7ff4bcf8> >,
<number.Number; proxy of <Swig Object of type 'Number *' at 0x7ff4b998> >)

>>> x.display() # call C++ method (like C++ x->display())
Number=2
>>> x.add(y.data) # fetch C++ data member, call C++ method
add 4
>>> x.display()
Number=6

>>> y.data = x.data + y.data + 32 # set C++ data member
>>> y.display() # y records the C++ this pointer
Number=42

>>> y.square() # method with return value
1764
>>> t = y.square()
>>> t, type(t) # type is class in Python 3.X
(1764, <class 'int'>)

Naturally, this example uses a small C++ class to underscore the basics, but even at
this level, the seamlessness of the Python-to-C++ integration we get from SWIG is
astonishing. Python code uses C++ members and methods as though they are Python
code. Moreover, this integration transparency still applies once we step up to more
realistic C++ class libraries.


So what’s the catch? Nothing much, really, but if you start using SWIG in earnest, the
biggest downside may be that SWIG cannot handle every feature of C++ today. If your
classes use some esoteric C++ tools (and there are many), you may need to handcode
simplified class type declarations for SWIG instead of running SWIG over the original
class header files. SWIG development is ongoing, so you should consult the SWIG
manuals and website for more details on these and other topics.


In return for any such trade-offs, though, SWIG can completely obviate the need to
code glue layers to access C and C++ libraries from Python scripts. If you have ever
coded such layers by hand in the past, you already know that this can be a very big win.


If you do go the handcoded route, though, consult Python’s standard extension man-
uals for more details on both API calls used in this chapter, as well as additional ex-
tension tools we don’t have space to cover in this text. C extensions can run the gamut
from short SWIG input files to code that is staunchly wedded to the internals of the
Python interpreter; as a rule of thumb, the former survives the ravages of time much
better than the latter.


Other Extending Tools


In closing the extending topic, I should mention that there are alternatives to SWIG,
many of which have a loyal user base of their own. This section briefly introduces some
of the more popular tools in this domain today; as usual, search the Web for more


Other Extending Tools | 1511
Free download pdf