[Tutor] Linking with C programs

Michael Sparks zathras at thwackety.com
Tue Sep 27 22:02:31 CEST 2005


On Tuesday 27 September 2005 14:49, Matt Williams wrote:
> Could someone explain how, in very general terms, one would use python
> to wrap some C libraries/ API.
>
> I ask because there are a few bits of C software that look quite
> interesting, and I know that Python can be used to wrap the C - but how
> does it work?

Use Pyrex. If you don't care about produce bindings for languages other than 
python and you just want access to C based libraries, then pyrex is by far 
the most pleasant way I've found of wrapping C.

Essentially pyrex is a bridge language - half C and half python. It compiles 
down to pure C, but handles all the awkward parts of bridging the two for 
you. (like handling ref counts and similar.)

We've used this to wrap a few libraries so far and it's been a pleasant 
experience everytime. It has a couple of tutorials, that work, and even shows 
you how to use distutils (aka setup.py) to make it easy for others to build 
your bindings too.

   * http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
   * http://ldots.org/pyrex-guide/ - Michael Smith's guide to Pyrex - it's IMO
      brilliant and the examples work, and if you're used to C and used to
      python just feels _natural_ .

If you're after a couple of examples to work forward, you can download them
from:
    * http://sourceforge.net/projects/kamaelia

Specifically the vorbissimple and python-dirac downloads will hopefully get 
you started. (The vorbissimple example includes a small simple library 
written in C and show hand off of data from python to C and from C to python, 
as well as how to have a "context" variable in C that python doesn't need to 
understand the internal structure of. (Much like with a FILE structure you 
don't need to understand the FILE structure's internals, just how you pass it 
about)

Regards,


Michael.


More information about the Tutor mailing list