G+: Doing horrible things with Python's ctypes and the …

David Coles
Doing horrible things with Python's ctypes and the new POSIX Alarm Timers interface in Linux 3.0. Upside: I can make my computer resume from suspend automatically using Python!

POSIX Alarm Timers in Python


(+1's) 4
Matt Giuca
Nice. I do share your concern with ctypes. It's pretty poor because of the need to duplicate header information. What we need is something that will parse (at runtime, if necessary) a C header file and produce a module object filled with ctypes objects, such as functions (for functions and parameterised macros), ctypes struct definitions (for structs) and values (for 0-argument macros). The hardest part would be producing the macros, because you would need a full C compiler. Maybe it would only support simple expressions -- that would do for a start.

There's a big advantage in using the old C/C++ API for writing Python extension modules. Yes, it's messy, painful, and less portable*, but it's often worth it for type safety and being able to reuse header files.

*Though I believe PyPy has it working now.

David Coles
The closest I've seen it ctypes_configure. Under the hood it uses Python distutils (same scripts that compile your Python C modules) so in theory it should work on all platforms that it supports. Of course it requires a compiler and development headers, but then that's just how C works. Being able to do this at runtime and having it cached (and able to auto-regenerate as necessary) would go a long way to making ctypes one of the most amazing modules in Python.

On the type-safety side, ctypes does let you specify an exact type signature (something I didn't know for a long time), but it's once again more duplication.

PyPy's C-API's seems pretty advanced these days, but still not up to using packages like NumPy and SciPy (though to get the biggest advantage out of PyPy's JIT you'd probably want to rewrite large parts in Python or RPython). C Modules are basically the only thing that stops me using PyPy over CPython these days.