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

(yzsuai) #1

imported, and we need both (scripts import the .py which in turn imports the .dll
internally).


As usual in C development, you may have to barter with the makefile to get it to work
on your system. Once you’ve run the makefile, though, you are finished. The generated
C module is used exactly like the manually coded version shown before, except that
SWIG has taken care of the complicated parts automatically. Function calls in our
Python code are routed through the generated SWIG layer, to the C code in Exam-
ple 20-4, and back again; with SWIG, this all “just works”:


.../PP4E/Integrate/Extend/Swig$ python
>>> import hellowrap # import glue + library file
>>> hellowrap.message('swig world') # cwd always searched on imports
'Hello, swig world'

>>> hellowrap.__file__
'hellowrap.py'
>>> dir(hellowrap)
['__builtins__', '__doc__', '__file__', '__name__', '_hellowrap', ... 'message']

>>> hellowrap._hellowrap
<module '_hellowrap' from '_hellowrap.dll'>

In other words, once you learn how to use SWIG, you can often largely forget the details
behind integration coding. In fact, SWIG is so adept at generating Python glue code
that it’s usually easier and less error prone to code C extensions for Python as purely
C- or C++-based libraries first, and later add them to Python by running their header
files through SWIG, as demonstrated here.


We’ve mostly just scratched the SWIG surface here, and there’s more for you to learn
about it from its Python-specific manual—available with SWIG at http://www.swig
.org. Although its examples in this book are simple, SWIG is powerful enough to in-
tegrate libraries as complex as Windows extensions and commonly used graphics APIs
such as OpenGL. We’ll apply it again later in this chapter, and explore its “shadow
class” model for wrapping C++ classes too. For now, let’s move on to a more useful
extension example.


Wrapping C Environment Calls


Our next example is a C extension module that integrates the standard C library’s
getenv and putenv shell environment variable calls for use in Python scripts. Exam-
ple 20-8 is a C file that achieves this goal in a hand-coded, manual fashion.


Example 20-8. PP4E\Integrate\Extend\Cenviron\cenviron.c


/**



  • A C extension module for Python, called "cenviron". Wraps the

  • C library's getenv/putenv routines for use in Python programs.
    **/


Wrapping C Environment Calls | 1495
Free download pdf