Richard Jones' Log: Working with ctypes has taught me...
I've been doing a bit of ctypes-based work lately. It's taught me a few things:
- ctypes is way cool and IronPython (which Anthony tells me - on a daily basis - is cool) needs full support ASAP.
- 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.
- 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.
- 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.