SlideShare a Scribd company logo
1 of 29
Download to read offline
Using SWIG to Control, Prototype,
       and Debug C Programs with Python
                    Dave Beazley

             Department of Computer Science
                    University of Utah
               Salt Lake City, Utah 84112
               beazley@cs.utah.edu

                       June 5, 1996




SWIG                         1                4th International Python Conference
Topics

       •   What is SWIG?

       •   Extending Python

       •   A Tour of SWIG

       •   Applications

       •   Limitations

       •   Work in progress and future directions




SWIG                           2                4th International Python Conference
SWIG (Simplified Wrapper and Interface Generator)

       •   Compiler that takes ANSI C/C++ declarations and produces
           bindings to interpreted languages.

       •   Supports almost all C/C++ datatypes

       •   Binds functions, variables, and constants

       •   C++ classes (including some inheritance)

       •   Run-time type-checking

       •   Supports modules and multiple files

       •   Automatic documentation generation

       •   Currently supports Python, Tcl, Perl4, Perl5, Guile3

       •   Extensible




SWIG                                    3                         4th International Python Conference
Where am I Coming From?
                                              Compilers
           Physics/                                               Debugging
           Numerical       Rapid Prototyping
           Analysis
                       100 Gbytes                 Dave’s
                                                  Scripting                    ML
                       of Data
                                                  Language


                        @#**$!                    SWIG
                                                  Prototype


         “Tools”          Dave’s
                          Attitude            Python                Perl
                          Problem
                                     Tcl/Tk                                    Guile

                           Ease of Use
                                                  SWIG
                          Documentation
       Physicists

SWIG                         4                         4th International Python Conference
The Two Language Model
•      Two languages are better than one
•      C/C++
         •   Performance
         •   Hard-core number crunching
         •   Portability
         •   Complicated stuff

•      Python
         •   Control language
         •   Cool things like lists, associative arrays, modules, etc...
         •   Interpreted
         •   Good extension language
         •   Rapid prototyping
         •   Debugging
         •   User interfaces (tkinter)

•      Use the best features of each language


SWIG                                   5                       4th International Python Conference
Extending Python
Suppose you wanted to add the getenv() function
to Python.
                                 A Python wrapper function
•      Need to write special
                                  static PyObject *wrap_getenv(
       “wrapper” functions.           PyObject *self,
                                      PyObject *args)
•      Fortunately, it’s          {
       usually not too
       difficult.                     char *result;
                                      char *arg0;
                                      if (!PyArg_ParseTuple(args,”s”,&arg0))
•      But, imagine doing                   return NULL;
       this for 200 functions.        result = getenv(arg0);
                                      return Py_BuildValue(“s”,result);
•      Tedious and error          }
       prone.



 Procedure is about the same for most other scripting
 languages (some are easier than others).

SWIG                                       6                      4th International Python Conference
SWIG Overview
•      Interface file with                 Interface file
       ANSI C/C++

•      Generic YACC                            Parser
       Parser

•      Target languages
       are C++ classes.        Code                     Doc.
                               Generator                Generator

•      Easy to extend
       (well mostly).

•      Produces a C/C++            Python                      HTML
                                   Tcl                         LaTeX
       source file as output       Perl4                       ASCII
                                   Perl5
                                   Guile-iii


SWIG                           8                            4th International Python Conference
A Simple Example
  example.c                                  example.i (SWIG Interface File)

                                              %module example
   int fact(int n) {                          %{
       if (n <= 1) return 1;                  // Insert headers here
       else return(n*fact(n-1));              %}
   }                                          extern int fact(int);




       unix% swig -python example.i
       unix% gcc -c example.c example_wrap.c -I/usr/local/include/Py
       unix% ld -shared example.o example_wrap.o -o example.so
       unix% python1.3
       Python1.3 (Apr 12 1996)   [GCC 2.5.8]
       Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
       >>> from example import *
       >>> n = fact(6);
       >>> print n
       720
       >>>



SWIG                                    9                      4th International Python Conference
SWIG Datatypes
 •     Built-in types:
       int, short, long, char, float, double, void

       (integers can also be signed or unsigned).

 •     Derived types:
       •   Pointers to built-in types.
       •   Pointers to structures
       •   Pointers to objects
       •   Well, almost any kind of pointer actually....

       In fact, all derived types are pointers in SWIG (but more on that
       in a minute).

 •     Can remap types using typedef
 •     The bottom line :
       •   Almost all C/C++ datatypes can be used.
       •   No pointers to functions (unless hidden via typedef).
       •   Arrays a little weird too...

SWIG                                    10                      4th International Python Conference
Adding Functions
•      SWIG uses ANSI C/C++ prototypes :

                int        foo(int a, int b);
       extern   void       print_data(double **);
       unsigned int        f1(void), f2();
       extern   int        strcmp(const char *, const char *);
                struct tm *localtime(long *t);
                double   **new_matrix(int n, int m);
                Node      *get_node(char *);
                int        Foo::bar();

•      All built-in types and derived types allowed

•      No type information needed for complex datatypes
       (ie. Node or struct tm).

•      Usually pretty easy to use header files.

•      Parser throws out some clutter (inline code, etc...)

SWIG                           11                 4th International Python Conference
Linking to C Variables and Constants
•      Access global variables by declaring them
       double My_variable;
       extern int flag;
       Node   *root;

       (In python this creates functions such as the following :)
       double My_variable_get();
       double My_variable_set(double newvalue);

•      Create constants with #define, enum, or const
       #define MODE    1
       enum colors {red, blue, green, yellow, brown};
       const int FLAGS = 0x04000020;

•      Constant expressions allowed
       #define STATUS    0x20 | 0x1 | 0x1000
       const double PI_4 = PI/4;



SWIG                                     12                         4th International Python Conference
Pointers
•      All derived types in SWIG are pointers.

•      Encoded as strings with type information
          Example:      _1008e124_Vector_p

       (Hmmm.... perhaps a carry over from Tcl)

•      Checked at run-time for validity
          >>> n = new_Node()
          >>> v = new_Vector(3,5,10)
          >>> d = dot(v,n)
          Traceback (innermost last):
              File “”, line 1, in ?
          TypeError: Type error in argument 2 of dot.
          Expected _Vector_p.
          >>>
•      Type-checker is savvy to typedef and C++.
•      Prevents crashes due to stupid mistakes.
SWIG                                  13          4th International Python Conference
SWIG and C++
  %module list                             List *new_List(void) {
  %{                                           return new List;
  #include “list.h”                        }
  %}
                                           void delete_List(List *l) {
  class List {                                 delete l;
  public:                                  }
      List();
     ~List();                              int List_search(List *l,
      int search(char *item);                              char *item) {
      void insert(char *item);                 return l->search(item);
      void remove(char *item);             }
      char *get(int n);                    ...
      int length;                          int List_length_get(List *l) {
  static void print(List *l);                  return l->length;
  };                                       }

                                           int List_length_set(List *l,
 • C++ code politely translated into C                         int value) {
                                               return (l->length = value);
                                           }
 • C functions are then wrapped.
                                           void List_print(List *l) {
 • Works independently of the                  List::print(l);
   target language.                        }

 • Can be fully customized (work in
   progress).

SWIG                                  14                     4th International Python Conference
SWIG and C++ (cont...)
•      Inheritance
       •   SWIG supports single public inheritance.
       •   Virtual functions okay.

•      Use of C++ references usually works

•      Limitations
       •   No operator overloading
       •   No templates.
       •   No multiple inheritance
       •   No function overloading (but you can rename things).

                                        List();
               %name(ListItem)          List(char *item);

•      Thoughts
       •   C++ is a complicated beast. Probably pretty hard to support all of
           it. I’ve tried to work with a reasonable subset.

       •   Wasn’t my intent to write a full C++ compiler.
SWIG                                    15                     4th International Python Conference
Multiple Files and Modules
•      Interfaces can be built from multiple files
       and libraries.

             %module package
             %{
             #include “package.h”
             %}

             %include   geometry.i
             %include   file.i
             %include   graphics.i
             %include   network.i
             %include   integration.i
             %include   mesh.i

•      Module system makes it very easy to reuse
       code in other packages.
•      SWIG comes with a library of stuff.

•      Code reuse that works??? (maybe)
SWIG                             16              4th International Python Conference
Documentation System
Documentation is generated automatically from
comments
  %title “My Interface”                             My Interface
  %module package
  %{                                                1.    Initialization
  #include “package.h”
  %}                                                void package.init()
                                                         Initializes the system
  %section “Initialization”
                                                    void package.haze()
  void init();                                           Initializes the system and spawns
  /* Initializes the system */                           an initiation ritual.
  void haze();
  /* Initializes the system and                     2.     Graphics
  spawns an initiation ritual */
                                                    void package.LoadMatrix(m)
  %section “Graphics”                                    Loads viewing transformation
                                                         matrix
  void LoadMatrix(Matrix *m);
  /* Loads viewing transformation matrix */         void package.ClearBuffer(color)
  void ClearBuffer(int color);                           Clear the frame buffer
  /* Clear the frame buffer */
                                                    3.     Network
  %section “Network”
                                                    int    package.open_socket(host, port)
  int open_socket(char *host, int port);                   Open up a connection with the server
  /* Open up a connection with the server */
                                                    void package.disconnect(fd)
  void disconnect(int fd);                               Close connection.
  /* Close connection */




SWIG                                           17                              4th International Python Conference
Controlling C Programs
•      SWIG requires virtually no modification to C code.

•      Easy to use with existing applications

•      Currently used at Los Alamos with the SPaSM
       Molecular Dynamics code
          •   ~250 functions and variables

          •   Used on CM-5, T3D, Workstations

          •   SWIG is hidden in the Makefile and is completely
              transparent to the users

•      Simplicity of approach is particularly attractive in
       research applications.



SWIG                                  18                     4th International Python Conference
Building Python Modules and Classes
•      Can build Python modules out of C/C++ libraries.

         Example : MATLAB, OpenGL, etc...

•      Can encapsulate C++ classes (with a little work)
%module tree                             import tree
%{
#include “tree.h”                        class Tree:
%}                                           def __init__(self):
                                               self.ptr = new_Tree()
class Tree {                                 def __del__(self):
public:                                        delete_Tree(self.ptr)
    Tree();                                  def insert(self,key,val):
    ~Tree();                                   Tree_insert(self.ptr,key,val)
    void insert(char *key,char *val);        def search(self,key):
    char *search(char *key);                   v = Tree_search(self.ptr,key)
    void remove(char *key);                    return v
};                                           def remove(self,key):
                                               Tree_remove(self.ptr,key)



 •     Combining various modules usually leads to
       interesting applications

SWIG                                19                       4th International Python Conference
Prototyping and Debugging
•      SWIG works well if you want to interact with and
       debug C/C++ code.
•      Example : OpenGL
       %module opengl
       %{
       %}
       %include gl.i            //   All of the OpenGL library
       %include glu.i           //   Most of the GLU library
       %include aux.i           //   Most of the GL aux library
       %include help.i          //   A few functions added to help out

       Each include file is just an edited copy of various GL header files.

       Total development time ~ 20 minutes.

           •   708 Constants

           •   426 Functions

           •   > 8000 lines of wrapper code.


SWIG                                    20                       4th International Python Conference
OpenGL Example
 from opengl import *

 def myinit ():
      light_ambient = newfv4( 0.0, 0.0, 0.0, 1.0 );
      light_diffuse = newfv4( 1.0, 1.0, 1.0, 1.0 );
      light_specular = newfv4( 1.0, 1.0, 1.0, 1.0 );
      light_position = newfv4( 1.0, 1.0, 1.0, 0.0 );
      glLightfv (GL_LIGHT0, GL_AMBIENT, light_ambient);
      glLightfv (GL_LIGHT0, GL_DIFFUSE, light_diffuse);
      glLightfv (GL_LIGHT0, GL_SPECULAR, light_specular);
      glLightfv (GL_LIGHT0, GL_POSITION, light_position);
      glEnable (GL_LIGHTING);
      glEnable (GL_LIGHT0);
      glDepthFunc(GL_LESS);
      glEnable(GL_DEPTH_TEST);

 def display ():
     glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
     glPushMatrix ();
     glRotatef (20.0, 1.0, 0.0, 0.0);
     glPushMatrix ();
     glTranslatef (-0.75, 0.5, 0.0);
     glRotatef (90.0, 1.0, 0.0, 0.0);
     auxSolidTorus (0.275, 0.85);
     glPopMatrix ();
     glPushMatrix ();
     glTranslatef (-0.75, -0.5, 0.0);
     glRotatef (270.0, 1.0, 0.0, 0.0);
     auxSolidCone (1.0, 2.0);
     glPopMatrix ();
     glPushMatrix ();
     glTranslatef (0.75, 0.0, -1.0);
     auxSolidSphere (1.0);
     glPopMatrix ();
     glPopMatrix ();
     glFlush ();



SWIG                                          21            4th International Python Conference
Current Limitations
 •     Lack of variable linking in Python
          Ex.
          double MyVariable ----> MyVariable_get(), MyVariable_set()

 •     Representing pointers as strings is a little weird
       (But you often don’t notice)

 •     Handling of C++ classes not complete. Often
       have to write a Python wrapper class afterwards

 •     Pointer model is sometimes confusing

 •     No exception model

 •     Numerical representation problems (particularly
       unsigned integers and longs)

 •     C++ parsing---need I say more?
SWIG                               23                     4th International Python Conference
A Few Projects Using SWIG

•      Materials Science Simulations (Los Alamos)
       •   SWIG used for nearly a year.
       •   System has worked flawlessly.

•      Defibrillation research (Univ. of Utah).
       •   Being used to glue together simulation, mesh
           generation and visualization code using Tcl/Tk.

•      Synthetic workload generation (Univ. of Utah)

•      OpenGL widget (Peter-Pike Sloan, Univ. of Utah)

•      ... and many other projects underway.




SWIG                                   22                    4th International Python Conference
Future Directions
•      Release of 1.0 Final (someday)
•      Continued improvement to Python implementation
           •   Perhaps a new pointer representation
           •   Better method for linking with variables
           •   Improved C++ support.
           •   An exception model???

•      Integration with Numerical Python?
•      Python for parallel machines?
       (A little unrelated, but I’d like it)

•      Support for new target languages (as appropriate)
           •   Java (well, maybe)
           •   ILU
           •   iTcl

•      Support for non-Unix platforms (in progress)
•      Whatever else comes up...

SWIG                                           24         4th International Python Conference
Acknowledgments

 •     All of the current users who have provided feedback, bug reports,
       and ideas.

 •     The first users :

       Kurtis Bleeker, Tim Germann, Brad Holian, Peter Lomdahl,
       John Schmidt, Peter-Pike Sloan, Shujia Zhou

 •     John Buckman (non-unix platforms and lots of good ideas)

 •     Patrick Tullmann (automatic documentation generation)

 •     The Scientific Computing and Imaging Group

 •     Oh, and these agencies paid some of my salary and provided machines

                DOE, NSF, NIH




SWIG                                        27                    4th International Python Conference
Advertisement

  The SWIG source code and user manual are
  available via anonymous FTP:
       ftp.cs.utah.edu/pub/beazley/SWIG

  The SWIG homepage:
       http://www.cs.utah.edu/~beazley/SWIG

  The SWIG mailing list:
       swig@cs.utah.edu




SWIG                       28             4th International Python Conference
Conclusions
•      SWIG Eliminates alot of the grungy details
       of integrating C/C++ with Python

•      Current system supports a reasonable subset of
       C and C++.

•      Two-language model is where it’s at.

•      Many users like the easy of use and straightforward
       approach.

•      I developed SWIG for myself---and I find myself
       using it almost all of the time (but, I’m probably
       biased).




SWIG                           26                4th International Python Conference
Automatic Wrapper Generation
•      Most languages have tools for automatically
       generating wrapper code.
          ex.   ILU, Modulator, Object Tcl, XS, etc...

•      Most tools are specific to a single language
•      Use of special syntax (or formatting)
•      Difficult to use.

SWIG :

•      Use ANSI C/C++ specifications (independent of
       target language).

•      Try to keep it simple, yet flexible.

•      I hate religious wars....
SWIG                                   7                 4th International Python Conference
Random Thoughts
•      SWIG vs. hand-written modules
       •   SWIG was not really designed to be a generic module builder

•      Performance concerns
       •   You don’t use interpreted languages if you want performance.
       •   2 Language Module ===> Write critical stuff in C/C++

•      Security and Reliability
       •   Type-checker eliminates alot of problems.
       •   Can still forge bogus pointer values.
       •   C++ is always a little risky (pointer casting problems for instance).

•      Coding Methodology
       •   When used during code development, SWIG encourages modularity.
       •   Usually results in more reliable and flexible code.

•      Why all of the Effort?
       •   I want to have a useful and reliable tool.

SWIG                                     25                      4th International Python Conference
Building a SWIG Extension
•      Need to supply a new language class
       (about a dozen functions).

•      Write a main program like this :
#include <swig.h>
#include <my_python.h>

int main(int argc, char **argv) {
   PYTHON   *l;

       l = new PYTHON;
       SWIG_main(argc,argv,l,(Documentation *) 0);
       return 0;
}

•      Recompile
unix > g++ my_python.C main.C -lswig -o myswig

•      Unfortunately, the code in my_python.C is
       pretty ugly (working on it).
SWIG                                            4th International Python Conference

More Related Content

What's hot

An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...David Beazley (Dabeaz LLC)
 
Using Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard IIUsing Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard IIDavid Beazley (Dabeaz LLC)
 
Generator Tricks for Systems Programmers, v2.0
Generator Tricks for Systems Programmers, v2.0Generator Tricks for Systems Programmers, v2.0
Generator Tricks for Systems Programmers, v2.0David Beazley (Dabeaz LLC)
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonYi-Lung Tsai
 
Ry pyconjp2015 karaoke
Ry pyconjp2015 karaokeRy pyconjp2015 karaoke
Ry pyconjp2015 karaokeRenyuan Lyu
 
Python on a chip
Python on a chipPython on a chip
Python on a chipstoggi
 
In Search of the Perfect Global Interpreter Lock
In Search of the Perfect Global Interpreter LockIn Search of the Perfect Global Interpreter Lock
In Search of the Perfect Global Interpreter LockDavid Beazley (Dabeaz LLC)
 
pyconjp2015_talk_Translation of Python Program__
pyconjp2015_talk_Translation of Python Program__pyconjp2015_talk_Translation of Python Program__
pyconjp2015_talk_Translation of Python Program__Renyuan Lyu
 
PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimeNational Cheng Kung University
 
Sour Pickles
Sour PicklesSour Pickles
Sour PicklesSensePost
 
Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Carlos Miguel Ferreira
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windowsextremecoders
 

What's hot (20)

Generator Tricks for Systems Programmers
Generator Tricks for Systems ProgrammersGenerator Tricks for Systems Programmers
Generator Tricks for Systems Programmers
 
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
 
Easy native wrappers with SWIG
Easy native wrappers with SWIGEasy native wrappers with SWIG
Easy native wrappers with SWIG
 
Mastering Python 3 I/O
Mastering Python 3 I/OMastering Python 3 I/O
Mastering Python 3 I/O
 
Python in Action (Part 2)
Python in Action (Part 2)Python in Action (Part 2)
Python in Action (Part 2)
 
Using Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard IIUsing Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard II
 
Understanding the Python GIL
Understanding the Python GILUnderstanding the Python GIL
Understanding the Python GIL
 
Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)
 
Generator Tricks for Systems Programmers, v2.0
Generator Tricks for Systems Programmers, v2.0Generator Tricks for Systems Programmers, v2.0
Generator Tricks for Systems Programmers, v2.0
 
An Introduction to Python Concurrency
An Introduction to Python ConcurrencyAn Introduction to Python Concurrency
An Introduction to Python Concurrency
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded Python
 
Ry pyconjp2015 karaoke
Ry pyconjp2015 karaokeRy pyconjp2015 karaoke
Ry pyconjp2015 karaoke
 
Generators: The Final Frontier
Generators: The Final FrontierGenerators: The Final Frontier
Generators: The Final Frontier
 
Python on a chip
Python on a chipPython on a chip
Python on a chip
 
In Search of the Perfect Global Interpreter Lock
In Search of the Perfect Global Interpreter LockIn Search of the Perfect Global Interpreter Lock
In Search of the Perfect Global Interpreter Lock
 
pyconjp2015_talk_Translation of Python Program__
pyconjp2015_talk_Translation of Python Program__pyconjp2015_talk_Translation of Python Program__
pyconjp2015_talk_Translation of Python Program__
 
PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtime
 
Sour Pickles
Sour PicklesSour Pickles
Sour Pickles
 
Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
 

Similar to Using SWIG to Control, Prototype, and Debug C Programs with Python

Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unitmichaelaaron25322
 
What is Python? (Silicon Valley CodeCamp 2015)
What is Python? (Silicon Valley CodeCamp 2015)What is Python? (Silicon Valley CodeCamp 2015)
What is Python? (Silicon Valley CodeCamp 2015)wesley chun
 
What is Python? (Silicon Valley CodeCamp 2014)
What is Python? (Silicon Valley CodeCamp 2014)What is Python? (Silicon Valley CodeCamp 2014)
What is Python? (Silicon Valley CodeCamp 2014)wesley chun
 
The Joy of SciPy
The Joy of SciPyThe Joy of SciPy
The Joy of SciPykammeyer
 
Python 101 for the .NET Developer
Python 101 for the .NET DeveloperPython 101 for the .NET Developer
Python 101 for the .NET DeveloperSarah Dutkiewicz
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsHenry Schreiner
 
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Foundation
 
Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfPython_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfbhagyashri686896
 
Python_final_print_batch_II_vision_academy (1).pdf
Python_final_print_batch_II_vision_academy (1).pdfPython_final_print_batch_II_vision_academy (1).pdf
Python_final_print_batch_II_vision_academy (1).pdfrupaliakhute
 
Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfPython_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfsannykhopade
 
Python_vision_academy notes
Python_vision_academy notes Python_vision_academy notes
Python_vision_academy notes rajaniraut
 
PyQt Application Development On Maemo
PyQt Application Development On MaemoPyQt Application Development On Maemo
PyQt Application Development On Maemoachipa
 
Complete python toolbox for modern developers
Complete python toolbox for modern developersComplete python toolbox for modern developers
Complete python toolbox for modern developersJan Giacomelli
 
Monitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntopMonitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntopPyCon Italia
 
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdfPython_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdfVisionAcademyProfSac
 
Socket Programming In Python
Socket Programming In PythonSocket Programming In Python
Socket Programming In Pythondidip
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Python for Science and Engineering: a presentation to A*STAR and the Singapor...
Python for Science and Engineering: a presentation to A*STAR and the Singapor...Python for Science and Engineering: a presentation to A*STAR and the Singapor...
Python for Science and Engineering: a presentation to A*STAR and the Singapor...pythoncharmers
 

Similar to Using SWIG to Control, Prototype, and Debug C Programs with Python (20)

Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
 
What is Python? (Silicon Valley CodeCamp 2015)
What is Python? (Silicon Valley CodeCamp 2015)What is Python? (Silicon Valley CodeCamp 2015)
What is Python? (Silicon Valley CodeCamp 2015)
 
What is Python? (Silicon Valley CodeCamp 2014)
What is Python? (Silicon Valley CodeCamp 2014)What is Python? (Silicon Valley CodeCamp 2014)
What is Python? (Silicon Valley CodeCamp 2014)
 
The Joy of SciPy
The Joy of SciPyThe Joy of SciPy
The Joy of SciPy
 
Python 101 for the .NET Developer
Python 101 for the .NET DeveloperPython 101 for the .NET Developer
Python 101 for the .NET Developer
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
 
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11
 
Python for Delphi Developers - Part 2
Python for Delphi Developers - Part 2Python for Delphi Developers - Part 2
Python for Delphi Developers - Part 2
 
Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfPython_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdf
 
Python_final_print_batch_II_vision_academy (1).pdf
Python_final_print_batch_II_vision_academy (1).pdfPython_final_print_batch_II_vision_academy (1).pdf
Python_final_print_batch_II_vision_academy (1).pdf
 
Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfPython_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdf
 
Python_vision_academy notes
Python_vision_academy notes Python_vision_academy notes
Python_vision_academy notes
 
PyQt Application Development On Maemo
PyQt Application Development On MaemoPyQt Application Development On Maemo
PyQt Application Development On Maemo
 
Complete python toolbox for modern developers
Complete python toolbox for modern developersComplete python toolbox for modern developers
Complete python toolbox for modern developers
 
Monitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntopMonitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntop
 
A Python Tutorial
A Python TutorialA Python Tutorial
A Python Tutorial
 
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdfPython_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
 
Socket Programming In Python
Socket Programming In PythonSocket Programming In Python
Socket Programming In Python
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Python for Science and Engineering: a presentation to A*STAR and the Singapor...
Python for Science and Engineering: a presentation to A*STAR and the Singapor...Python for Science and Engineering: a presentation to A*STAR and the Singapor...
Python for Science and Engineering: a presentation to A*STAR and the Singapor...
 

Recently uploaded

Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...itnewsafrica
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 

Recently uploaded (20)

Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 

Using SWIG to Control, Prototype, and Debug C Programs with Python

  • 1. Using SWIG to Control, Prototype, and Debug C Programs with Python Dave Beazley Department of Computer Science University of Utah Salt Lake City, Utah 84112 beazley@cs.utah.edu June 5, 1996 SWIG 1 4th International Python Conference
  • 2. Topics • What is SWIG? • Extending Python • A Tour of SWIG • Applications • Limitations • Work in progress and future directions SWIG 2 4th International Python Conference
  • 3. SWIG (Simplified Wrapper and Interface Generator) • Compiler that takes ANSI C/C++ declarations and produces bindings to interpreted languages. • Supports almost all C/C++ datatypes • Binds functions, variables, and constants • C++ classes (including some inheritance) • Run-time type-checking • Supports modules and multiple files • Automatic documentation generation • Currently supports Python, Tcl, Perl4, Perl5, Guile3 • Extensible SWIG 3 4th International Python Conference
  • 4. Where am I Coming From? Compilers Physics/ Debugging Numerical Rapid Prototyping Analysis 100 Gbytes Dave’s Scripting ML of Data Language @#**$! SWIG Prototype “Tools” Dave’s Attitude Python Perl Problem Tcl/Tk Guile Ease of Use SWIG Documentation Physicists SWIG 4 4th International Python Conference
  • 5. The Two Language Model • Two languages are better than one • C/C++ • Performance • Hard-core number crunching • Portability • Complicated stuff • Python • Control language • Cool things like lists, associative arrays, modules, etc... • Interpreted • Good extension language • Rapid prototyping • Debugging • User interfaces (tkinter) • Use the best features of each language SWIG 5 4th International Python Conference
  • 6. Extending Python Suppose you wanted to add the getenv() function to Python. A Python wrapper function • Need to write special static PyObject *wrap_getenv( “wrapper” functions. PyObject *self, PyObject *args) • Fortunately, it’s { usually not too difficult. char *result; char *arg0; if (!PyArg_ParseTuple(args,”s”,&arg0)) • But, imagine doing return NULL; this for 200 functions. result = getenv(arg0); return Py_BuildValue(“s”,result); • Tedious and error } prone. Procedure is about the same for most other scripting languages (some are easier than others). SWIG 6 4th International Python Conference
  • 7. SWIG Overview • Interface file with Interface file ANSI C/C++ • Generic YACC Parser Parser • Target languages are C++ classes. Code Doc. Generator Generator • Easy to extend (well mostly). • Produces a C/C++ Python HTML Tcl LaTeX source file as output Perl4 ASCII Perl5 Guile-iii SWIG 8 4th International Python Conference
  • 8. A Simple Example example.c example.i (SWIG Interface File) %module example int fact(int n) { %{ if (n <= 1) return 1; // Insert headers here else return(n*fact(n-1)); %} } extern int fact(int); unix% swig -python example.i unix% gcc -c example.c example_wrap.c -I/usr/local/include/Py unix% ld -shared example.o example_wrap.o -o example.so unix% python1.3 Python1.3 (Apr 12 1996) [GCC 2.5.8] Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> from example import * >>> n = fact(6); >>> print n 720 >>> SWIG 9 4th International Python Conference
  • 9. SWIG Datatypes • Built-in types: int, short, long, char, float, double, void (integers can also be signed or unsigned). • Derived types: • Pointers to built-in types. • Pointers to structures • Pointers to objects • Well, almost any kind of pointer actually.... In fact, all derived types are pointers in SWIG (but more on that in a minute). • Can remap types using typedef • The bottom line : • Almost all C/C++ datatypes can be used. • No pointers to functions (unless hidden via typedef). • Arrays a little weird too... SWIG 10 4th International Python Conference
  • 10. Adding Functions • SWIG uses ANSI C/C++ prototypes : int foo(int a, int b); extern void print_data(double **); unsigned int f1(void), f2(); extern int strcmp(const char *, const char *); struct tm *localtime(long *t); double **new_matrix(int n, int m); Node *get_node(char *); int Foo::bar(); • All built-in types and derived types allowed • No type information needed for complex datatypes (ie. Node or struct tm). • Usually pretty easy to use header files. • Parser throws out some clutter (inline code, etc...) SWIG 11 4th International Python Conference
  • 11. Linking to C Variables and Constants • Access global variables by declaring them double My_variable; extern int flag; Node *root; (In python this creates functions such as the following :) double My_variable_get(); double My_variable_set(double newvalue); • Create constants with #define, enum, or const #define MODE 1 enum colors {red, blue, green, yellow, brown}; const int FLAGS = 0x04000020; • Constant expressions allowed #define STATUS 0x20 | 0x1 | 0x1000 const double PI_4 = PI/4; SWIG 12 4th International Python Conference
  • 12. Pointers • All derived types in SWIG are pointers. • Encoded as strings with type information Example: _1008e124_Vector_p (Hmmm.... perhaps a carry over from Tcl) • Checked at run-time for validity >>> n = new_Node() >>> v = new_Vector(3,5,10) >>> d = dot(v,n) Traceback (innermost last): File “”, line 1, in ? TypeError: Type error in argument 2 of dot. Expected _Vector_p. >>> • Type-checker is savvy to typedef and C++. • Prevents crashes due to stupid mistakes. SWIG 13 4th International Python Conference
  • 13. SWIG and C++ %module list List *new_List(void) { %{ return new List; #include “list.h” } %} void delete_List(List *l) { class List { delete l; public: } List(); ~List(); int List_search(List *l, int search(char *item); char *item) { void insert(char *item); return l->search(item); void remove(char *item); } char *get(int n); ... int length; int List_length_get(List *l) { static void print(List *l); return l->length; }; } int List_length_set(List *l, • C++ code politely translated into C int value) { return (l->length = value); } • C functions are then wrapped. void List_print(List *l) { • Works independently of the List::print(l); target language. } • Can be fully customized (work in progress). SWIG 14 4th International Python Conference
  • 14. SWIG and C++ (cont...) • Inheritance • SWIG supports single public inheritance. • Virtual functions okay. • Use of C++ references usually works • Limitations • No operator overloading • No templates. • No multiple inheritance • No function overloading (but you can rename things). List(); %name(ListItem) List(char *item); • Thoughts • C++ is a complicated beast. Probably pretty hard to support all of it. I’ve tried to work with a reasonable subset. • Wasn’t my intent to write a full C++ compiler. SWIG 15 4th International Python Conference
  • 15. Multiple Files and Modules • Interfaces can be built from multiple files and libraries. %module package %{ #include “package.h” %} %include geometry.i %include file.i %include graphics.i %include network.i %include integration.i %include mesh.i • Module system makes it very easy to reuse code in other packages. • SWIG comes with a library of stuff. • Code reuse that works??? (maybe) SWIG 16 4th International Python Conference
  • 16. Documentation System Documentation is generated automatically from comments %title “My Interface” My Interface %module package %{ 1. Initialization #include “package.h” %} void package.init() Initializes the system %section “Initialization” void package.haze() void init(); Initializes the system and spawns /* Initializes the system */ an initiation ritual. void haze(); /* Initializes the system and 2. Graphics spawns an initiation ritual */ void package.LoadMatrix(m) %section “Graphics” Loads viewing transformation matrix void LoadMatrix(Matrix *m); /* Loads viewing transformation matrix */ void package.ClearBuffer(color) void ClearBuffer(int color); Clear the frame buffer /* Clear the frame buffer */ 3. Network %section “Network” int package.open_socket(host, port) int open_socket(char *host, int port); Open up a connection with the server /* Open up a connection with the server */ void package.disconnect(fd) void disconnect(int fd); Close connection. /* Close connection */ SWIG 17 4th International Python Conference
  • 17. Controlling C Programs • SWIG requires virtually no modification to C code. • Easy to use with existing applications • Currently used at Los Alamos with the SPaSM Molecular Dynamics code • ~250 functions and variables • Used on CM-5, T3D, Workstations • SWIG is hidden in the Makefile and is completely transparent to the users • Simplicity of approach is particularly attractive in research applications. SWIG 18 4th International Python Conference
  • 18. Building Python Modules and Classes • Can build Python modules out of C/C++ libraries. Example : MATLAB, OpenGL, etc... • Can encapsulate C++ classes (with a little work) %module tree import tree %{ #include “tree.h” class Tree: %} def __init__(self): self.ptr = new_Tree() class Tree { def __del__(self): public: delete_Tree(self.ptr) Tree(); def insert(self,key,val): ~Tree(); Tree_insert(self.ptr,key,val) void insert(char *key,char *val); def search(self,key): char *search(char *key); v = Tree_search(self.ptr,key) void remove(char *key); return v }; def remove(self,key): Tree_remove(self.ptr,key) • Combining various modules usually leads to interesting applications SWIG 19 4th International Python Conference
  • 19. Prototyping and Debugging • SWIG works well if you want to interact with and debug C/C++ code. • Example : OpenGL %module opengl %{ %} %include gl.i // All of the OpenGL library %include glu.i // Most of the GLU library %include aux.i // Most of the GL aux library %include help.i // A few functions added to help out Each include file is just an edited copy of various GL header files. Total development time ~ 20 minutes. • 708 Constants • 426 Functions • > 8000 lines of wrapper code. SWIG 20 4th International Python Conference
  • 20. OpenGL Example from opengl import * def myinit (): light_ambient = newfv4( 0.0, 0.0, 0.0, 1.0 ); light_diffuse = newfv4( 1.0, 1.0, 1.0, 1.0 ); light_specular = newfv4( 1.0, 1.0, 1.0, 1.0 ); light_position = newfv4( 1.0, 1.0, 1.0, 0.0 ); glLightfv (GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv (GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv (GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv (GL_LIGHT0, GL_POSITION, light_position); glEnable (GL_LIGHTING); glEnable (GL_LIGHT0); glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST); def display (): glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix (); glRotatef (20.0, 1.0, 0.0, 0.0); glPushMatrix (); glTranslatef (-0.75, 0.5, 0.0); glRotatef (90.0, 1.0, 0.0, 0.0); auxSolidTorus (0.275, 0.85); glPopMatrix (); glPushMatrix (); glTranslatef (-0.75, -0.5, 0.0); glRotatef (270.0, 1.0, 0.0, 0.0); auxSolidCone (1.0, 2.0); glPopMatrix (); glPushMatrix (); glTranslatef (0.75, 0.0, -1.0); auxSolidSphere (1.0); glPopMatrix (); glPopMatrix (); glFlush (); SWIG 21 4th International Python Conference
  • 21. Current Limitations • Lack of variable linking in Python Ex. double MyVariable ----> MyVariable_get(), MyVariable_set() • Representing pointers as strings is a little weird (But you often don’t notice) • Handling of C++ classes not complete. Often have to write a Python wrapper class afterwards • Pointer model is sometimes confusing • No exception model • Numerical representation problems (particularly unsigned integers and longs) • C++ parsing---need I say more? SWIG 23 4th International Python Conference
  • 22. A Few Projects Using SWIG • Materials Science Simulations (Los Alamos) • SWIG used for nearly a year. • System has worked flawlessly. • Defibrillation research (Univ. of Utah). • Being used to glue together simulation, mesh generation and visualization code using Tcl/Tk. • Synthetic workload generation (Univ. of Utah) • OpenGL widget (Peter-Pike Sloan, Univ. of Utah) • ... and many other projects underway. SWIG 22 4th International Python Conference
  • 23. Future Directions • Release of 1.0 Final (someday) • Continued improvement to Python implementation • Perhaps a new pointer representation • Better method for linking with variables • Improved C++ support. • An exception model??? • Integration with Numerical Python? • Python for parallel machines? (A little unrelated, but I’d like it) • Support for new target languages (as appropriate) • Java (well, maybe) • ILU • iTcl • Support for non-Unix platforms (in progress) • Whatever else comes up... SWIG 24 4th International Python Conference
  • 24. Acknowledgments • All of the current users who have provided feedback, bug reports, and ideas. • The first users : Kurtis Bleeker, Tim Germann, Brad Holian, Peter Lomdahl, John Schmidt, Peter-Pike Sloan, Shujia Zhou • John Buckman (non-unix platforms and lots of good ideas) • Patrick Tullmann (automatic documentation generation) • The Scientific Computing and Imaging Group • Oh, and these agencies paid some of my salary and provided machines DOE, NSF, NIH SWIG 27 4th International Python Conference
  • 25. Advertisement The SWIG source code and user manual are available via anonymous FTP: ftp.cs.utah.edu/pub/beazley/SWIG The SWIG homepage: http://www.cs.utah.edu/~beazley/SWIG The SWIG mailing list: swig@cs.utah.edu SWIG 28 4th International Python Conference
  • 26. Conclusions • SWIG Eliminates alot of the grungy details of integrating C/C++ with Python • Current system supports a reasonable subset of C and C++. • Two-language model is where it’s at. • Many users like the easy of use and straightforward approach. • I developed SWIG for myself---and I find myself using it almost all of the time (but, I’m probably biased). SWIG 26 4th International Python Conference
  • 27. Automatic Wrapper Generation • Most languages have tools for automatically generating wrapper code. ex. ILU, Modulator, Object Tcl, XS, etc... • Most tools are specific to a single language • Use of special syntax (or formatting) • Difficult to use. SWIG : • Use ANSI C/C++ specifications (independent of target language). • Try to keep it simple, yet flexible. • I hate religious wars.... SWIG 7 4th International Python Conference
  • 28. Random Thoughts • SWIG vs. hand-written modules • SWIG was not really designed to be a generic module builder • Performance concerns • You don’t use interpreted languages if you want performance. • 2 Language Module ===> Write critical stuff in C/C++ • Security and Reliability • Type-checker eliminates alot of problems. • Can still forge bogus pointer values. • C++ is always a little risky (pointer casting problems for instance). • Coding Methodology • When used during code development, SWIG encourages modularity. • Usually results in more reliable and flexible code. • Why all of the Effort? • I want to have a useful and reliable tool. SWIG 25 4th International Python Conference
  • 29. Building a SWIG Extension • Need to supply a new language class (about a dozen functions). • Write a main program like this : #include <swig.h> #include <my_python.h> int main(int argc, char **argv) { PYTHON *l; l = new PYTHON; SWIG_main(argc,argv,l,(Documentation *) 0); return 0; } • Recompile unix > g++ my_python.C main.C -lswig -o myswig • Unfortunately, the code in my_python.C is pretty ugly (working on it). SWIG 4th International Python Conference