Google

SWIG Python Examples

$Header: /cvs/projects/SWIG/Examples/python/index.html,v 1.8.4.2 2001/12/08 23:33:20 cheetah Exp $

The following examples illustrate the use of SWIG with Python.

  • simple. A minimal example showing how SWIG can be used to wrap a C function, a global variable, and a constant.
  • constants. This shows how preprocessor macros and certain C declarations are turned into constants.
  • variables. An example showing how to access C global variables from Python.
  • value. How to pass and return structures by value.
  • class. Wrapping a simple C++ class.
  • reference. C++ references.
  • pointer. Simple pointer handling.
  • funcptr. Pointers to functions.

Compilation Issues

  • To create a Python extension, SWIG is run with the following options:
    % swig -python interface.i
    
  • Please see the Windows page in the main manual for information on using the examples on Windows.

  • On Unix the compilation of examples is done using the file Example/Makefile. This makefile performs a manual module compilation which is platform specific. Typically, the steps look like this (Linux):
    % swig -python interface.i
    % gcc -fpic -c interface_wrap.c -I/usr/local/include/python1.5
    % gcc -shared interface_wrap.o $(OBJS) -o interfacemodule.so 
    % python
    Python 1.5.2 (#3, Oct  9 1999, 22:09:34)  [GCC 2.95.1 19990816 (release)] on linux2
    Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
    >>> import interface
    >>> interface.blah(...)
    ...
    
  • The politically "correct" way to compile a Python extension is to follow the steps described at www.python.org or in the most excellent (and shamelessly plugged) Python Essential Reference:

    1. Create a file called Setup that looks like the following where $(SRCS) is filled in with any other source files you need to build the extension:
      *shared*
      interface interface_wrap.c $(SRCS)
      
    2. Copy the file Makefile.pre.in from the Python distribution. Usually it's located in the directory /usr/local/lib/python1.5/config on a Unix machine.

    3. Type the following to build the extension:
      % make -f Makefile.pre.in boot
      % make
      
    4. And that's it. If you are preparing an extension for distribution, you may want to look at the distutils.

Compatibility

The examples have been extensively tested on the following platforms:
  • Linux
  • Solaris
All of the examples were last tested with the following configuration (9/1/2000):
  • Sparc Solaris 2.8.
  • gcc-2.95.2
  • Python 1.6b1.
Your mileage may vary. If you experience a problem, please let us know by sending a message to swig-dev@cs.uchicago.edu.