5.1.2.1 SWIG

SWIG (Standard Wrapper and Interface Generator) takes C++ (and C, etc.) libraries, and generates wrapper code so that the code can be used from within Python (and in several other interpreters). One writes interface files that describe how to make Python objects usable from your C++ code, and conversely what transformations C++ objects should undergo to be usable from Python.

In 2004, Stein considered using SWIG for SAGE extensively, and implemented several basic types using this model. The idea was to write code in C++ for SAGE that needed to be fast, then wrap it in SWIG. This ground to a halt, because the result was not sufficiently fast. First, there is overhead when writing code in C++ in the first place. Second, SWIG generates several layers of code between Python and the code that does the actual work; for implementing any of SAGE's numerous basic arithmetic type, e.g., integers, the overhead is completely unacceptable, at least if one wants code that is as fast as Magma and PARI. For example, in my initial implementation of integer arithmetic using SWIG and GMP, there were the following six levels between the SAGE interpreter and the GMP C library:

Python code to provide a clean interface
SWIG Autogenerated Python code
SWIG Autogenerated C++ extension code
Handcode C++ Integer class
GMP's C++ Interface
GMP C Library
In this model, just multiplying two integers is extremely complicated, and slow. Moreover, writing the SWIG interface files was painful, since general Python types are difficult to work with from C++ code. In contrast, with Cython the situation is as follows (see integer.pyx):
Cython generated C code that provides everything needed
GMP C Library
Another important problem with using SWIG is that developers have to know C++ well and have the mental dexterity to easily switch back and forth between C++ and Python. Stein does not have this ability.

See About this document... for information on suggesting changes.