Python ctypes Code Generator

| | Comments (0) | TrackBacks (0)
Maybe you too have some code you want to interface with a scripting language. Developers may have heard of SWIG. I admit, I've tried it with low success. I just couldn't be persuaded to keep at it long enough to get results. Usually I've had some thorny CPP template that just wasn't working out.

This week, I've been writing python as a base for an automated GUI testing infrastructure. Admittedly, still research and almost through that phase. I'm just turning the corner into productive.

This is because I've discovered python ctypes.
It took me less than 4 hours to read up, call functions into a 3rd party .dll that I have a header and source docs for. And get real results back. Sure beats inventing my own way to do the same things as that .dll interface.

Needing more functions from the .dll, I hunted around for a code generator that could take the header file as input. And sure enough, there it was. Ctypeslib is pretty interesting, but I'm having limited success at present.

With a little luck, I was able to write my own header that included the header I cared about and some other important ones. I was able to generate xml and export all of it as python. The problem is that it's cluttered (ok, it is generated!), it uses the absolute path to the library on my computer (harder to distribute, but search and replace works marvels!), and some of the functions and structs are malformed.

I went back, specified exactly the list of functions I wanted from the .dll, and generated a lot less code. Piped the output through sed to set the absolute path to the lib to a variable, and I now have more trim results. I'm in the midst of wrapping calls to the now-exposed functions so that they throw proper python Exceptions and return expected results. It's pretty sweet.

0 TrackBacks

Listed below are links to blogs that reference this entry: Python ctypes Code Generator.

TrackBack URL for this entry: http://skull.piratehaven.org/~epu/mt/mt-tb.cgi/12

Leave a comment

Recent Tweets