Richard Jones' Log: Working with ctypes has taught me...

Sat, 07 Oct 2006

I've been doing a bit of ctypes-based work lately. It's taught me a few things:

  1. ctypes is way cool and IronPython (which Anthony tells me - on a daily basis - is cool) needs full support ASAP.
  2. setjmp / longjmp are really quite nasty and should be avoided. ctypes is going to have to grow special support for setjmp so it can interface to certain libraries.
  3. Setting up Structure classes for C structs is a pain* and a little dodgy to boot**. I've been using a lot of c_void_p to handle structures that are being passed around (if I don't need to access structure members). This would scare the willies out of a C programmer (it would have scared me a few years back). I've spent long enough programming Python that I'm automatically careful about what I pass to functions. You know, the "we're all consenting adults" thing. I don't just pass any old crap, I pass what the function expects. No static typing crutches needed.
  4. The catch with using c_void_p everywhere is that ctypes turns the value into a regular Python int. This can cause problems if you then need to pass the address of the pointer somewhere. My work-around is to define a dummy Structure which I can use in place of "void".

*: Sometimes C headers can go out of their way to be obscure. Have a look at freetype's headers some day, starting with ft2build.h

**: I'm quite concerned that the code I have defined structures for will behave poorly on platforms where c_int != 32 bits, etc. My working knowledge of such portability issues is limited though, unfortunately. I guess that if it was a real issue then ctypes would provide 8-, 16-, 32- and 64-bit base types to work with.

Comment by Lawrence Oluyede on Sat, 07 Oct 2006

Hi Richard. Have you tried the code generator? It's here: it requires gccxml from cvs but works great. I wrapped some libs with that... it can actually save your day...

Comment by Richard Jones on Sat, 07 Oct 2006

Try on freetype's headers some day :)

Comment by Richard Jones on Sun, 08 Oct 2006

Actually, I can't get codegen to work on any of the libraries I wish to wrap.

Comment by Richard Jones on Mon, 09 Oct 2006

Oh, and ctypes does have sized ints (8-, 16-, 32- and 64-bit) ... they're just not documented in the first list of types in the manual. They are documented in the second list of types.