Peter's Blog

Redefining the Impossible

Python extension modules using Swig.


Decided to write a python extension module. Swig looks like the easiest way to do it. Given a simple definition file, e.g.:

%module mod552
extern int Wiffle( int a);
extern char *Poopie( char *strPoop);
extern int jetty( int a, char *strB);

%{
#include "Giblets.h"
%}

class Giblets
{
public:
  int Mandible( void);
};

Swig will generate a file full of c++ wrapper code for the python objects. The code for the library is written in straight C, e.g.:

   1  #include <string.h>
   2  #include <stdlib.h>
   3  #include "Giblets.h"
   4  
   5  int Wiffle( int a)
   6  {
   7      return a + 5;
   8  }
   9  
  10  char *Poopie( char *strPoop)
  11  {
  12      static char strBuff[1000];
  13  
  14      strcpy( strBuff, strPoop);
  15      strBuff[3] = 'p';
  16      strBuff[4] = 'c';
  17      strBuff[5] = 'w';
  18  
  19      return strBuff;
  20  }
  21  
  22  int jetty( int a, char *strB)
  23  {
  24      return a + atoi( strB);
  25  }
  26  
  27  int Giblets::Mandible( void)
  28  {
  29      return 97;
  30  }

The module is used in python as you would expect:

   1  C:\552\Src\Mod552\Mod552>python
   2  Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32
   3  Type "help", "copyright", "credits" or "license" for more information.
   4  >>> import mod552
   5  >>> dir(mod552)
   6  ['Giblets', 'GibletsPtr', 'Poopie', 'Wiffle', '__builtins__', '__doc__', '__file
   7  __', '__name__', '_mod552', '_newclass', '_object', '_swig_getattr', '_swig_seta
   8  ttr', 'jetty']
   9  >>> o = mod552.Giblets()
  10  >>> o.Mandible()
  11  97
  12  >>>

This article is a useful introduction to the process although you have to be savvy with Visual C++ to follow it.


Filed under: python swig

Comments are Closed