Wrapping a C library in Python

Roger Binns rogerb at rogerbinns.com
Mon Nov 22 11:33:37 EST 2004


"Roy Smith" <roy at panix.com> wrote in message news:roy-24C5BE.07565522112004 at reader1.panix.com...
> Since the handle is opaque, I don't need to know about the innards of
> the structure at all.  What I ended up doing was writing a little C
> routine something like this:
>
> dm_handle *allocate_dm_handle ()
> {
>   return malloc (sizeof (struct dm_handle));
> }
>
> I then built a .so containing just that one routine, and used ctypes to
> call it from Python to get my buffer.

Congralutions on just manually re-inventing Swig :-)  Unless your
library is trivial (which this code indicates it is not), I would
recommend also spending a little time with Swig.

In many cases Swig can parse your header files and build the
correct wrapper.  The huge advantage of Swig is that you can
use it to generate wrappers for a large number of languages.
That comes in really helpful if you will also need wrappers for
Java, TCL etc.

Roger 





More information about the Python-list mailing list