Wrapping a C library in Python

Michael Loritsch loritsch at gmail.com
Fri Nov 19 11:23:57 EST 2004


Roy Smith <roy at panix.com> wrote in message news:<roy-99F088.20103518112004 at reader1.panix.com>...
> I've got a C library with about 50 calls in it that I want to wrap in 
> Python.  I know I could use some tool like SWIG, but that will give me a 
> too-literal translation; I want to make some modifications along the way 
> to make the interface more Pythonic.
> 
> For example, all of these functions return an error code (typically just 
> errno passed along, but not always).  They all accept as one of their 
> arguments a pointer to someplace to store their result.  I want to 
> change all that to returning the result directly and throwing exceptions.
> 
> I also want to mutate some of the return types.  A common way these 
> functions return a set of values is a pair of arrays of strings, forming 
> key-value pairs.  In Python, it would make sense to return this as a 
> dictionary.
> 
> I know what I'm describing is kind of vague, but are there tools around 
> which might help automate (at least in part) this translation process?

While SWIG is a strong tool for wrapping C code into many different
langauges, there are definitely better tools out there for producing
python modules from C code.

I recommend both boost::python
(http://www.boost.org/libs/python/doc/index.html) and ctypes
(http://starship.python.net/crew/theller/ctypes/), but for very
different reasons.

If wrapped code speed and production of a binary is a goal in creating
your python extensions, use boost::python.  The price you pay for
creating an fast binary python extension is coding your translation
from python in C/C++ in C/C++ (I suppose you could get around this by
creating a boost::python module, and then wrapping it with a python
module to do the type translation).  And in boost::python, C++ to
python exception translation is supported.

If speed of development is your main goal, then I'd use ctypes. 
ctypes will dynamically load the library in python code.  At the
python code level, you should then do the translation to python types.
 No C/C++ coding required.

Hope this helps!

Michael Loritsch



More information about the Python-list mailing list