Ian Bicking: the old part of his blog

Nummy ctypes


Looking for Rewriting and Refactoring?

I recently used uTidyLib after mxTidy didn't immediately install for me (such impatience). uTidyLib doesn't ship with any C code, but uses ctypes to interface directory with libtidy (the library version of HTML tidy).

I thought that was clever. Then I looked at the actual code that does the interfacing; then I was really impressed: the entire interface to tidy is 216 lines long. It's not incredibly easy to understand -- it's glue code, after all -- but it's really not too bad. And it's so short!

Created 27 Apr '04
Modified 25 Jan '05


ctypes is pretty great, but caveat emptor..
(a) there's no automatic way to convert a C header to ctypes code
(b) some C-isms are terribly difficult to express in ctypes code
(c) debugging ctypes code is HARD

pyrex still has (a), partially solves (b), and almost entirely solves (c).
# Bob Ippolito

Where ctypes excels is deployment. It's very difficult to setup a build env. on w32 (see my docs on building Mnet on w32). For my ctypes based module I have one .py file, and the w32 users can copy the DLL need to c:\windows\system32 and be off and running.
# icepick

For deployment you can just as easily offer a precompiled pyd. It only takes one correctly configured environment in order to target windows.

FWIW, if you own VS.NET, it's easy to build on windows ;)
# Bob Ippolito

I mostly agree with Bob's three points, although for me (a) is not that important. I mainly use it to call win32 apis, and I gave up to wrap windows header files automatically, after some experiments (I got most far parsing header files with Simon Burton's cdecl.py module). Automatic wrapping may be more sucessful for simpler header files, if someone wants to work on this and submit code I'm open.

The ctypes.com package imo shows the real power of ctypes. And I don't want to fire up the C compiler for each and every new com interface I have to use. (Has anyone used pyrex to use com interfaces?)
# Thomas Heller

I think that Thomas uses APIs that take simple pointers and integers more often than I do ;) It seems that I have to write three or four lines of code, or more, per function call whenever I use ctypes.. which puts it more or less on par with Pyrex.

It's also half-broken on non-win32 platforms right now. Several important tests that should pass don't. This is where debugging is important. From gdb and pdb, it's REALLY hard to tell when and why it's ctypes fault.

I do like to experiment with ctypes, but I'll be damned if I use it in a production app any time soon :)
# Bob Ippolito

Of course it's partly broken on non-win32. I only left the cross-platform code because some users wanted it, but nobody so far complained or provided patches. I've seen that you posted a patch now, so it can improve.

I'll continue *this* discussion on the ctypes-users mailing list ;-)
# Thomas Heller