Saturday, April 25, 2009

Ctypes for IronPython

I've been spending the last little while working ctypes support for IronPython. It's certainly an interesting problem, mapping from Python –> .NET –> C, and I've learned more than I ever wanted to know about extending IronPython. Support isn't anywhere close to complete – it passes a whopping 5/101 tests. IronPython 2.6 is required.

What's complete:

  • Primitive (c_*) types
  • Simple structures, nested structures
  • Loading DLLs
  • Calling functions
  • byref() parameters

What's missing:

  • Unions
  • Subclassed structures
  • Arrays
  • Probably lots of other stuff…

It does work for simple functions, like so:

from ctypes import *

libc = cdll.msvcrt

i = c_int()
f = c_float()
libc.sscanf("1 3.14", "%d %f", byref(i), byref(f))

Download the DLL. Drop the DLL in the "DLLs" directory of your IronPython 2.6 installation (create it if it doesn't exist).

Huge thanks to Seo Sanghyeon for the original FePy implementation (written in Python – I'm still not sure rewriting in C# was a good idea) and Curt Hagenlocher for providing me with the code to generate types on the fly. If you want to check out the source, go to my hg repository. As always, the code is under the MS-PL.

UPDATE: It turns out ctypes will be part of IronPython 2.6 (not based on this code, but a completely different implementation).