Python code -> to C code

Thomas Heller theller at
Wed Apr 30 13:35:36 CEST 2003

Duncan Booth <duncan at> writes:

> Thomas Heller <theller at> wrote in news:bryo1gj6.fsf at
> > Normally this is used to implement "callback functions" in Python, to
> > call functions like Windows' EnumWindows(), or to implement COM object
> > method tables.
> > 
> > Does this count as embedding? It seems so, although I have never seen it
> > this way.
> I think it counts as half of embedding. It lets you call Python from C, 
> provided the C was called originally from Python. I don't see that it helps 
> at all with the situation in my original posting which was calling Python 
> from an otherwise purely C program.
> I'm impressed by the example wrapping qsort.


> I can't think offhand of a way to achieve this easily in Pyrex. That
> is, Pyrex could easily wrap qsort to call a specific Python function
> for the comparison, but there isn't anywhere in the qsort callback to
> store state, and I can't see how you manage to convert a Python
> function into a C level function without some additional state.

Right. Actually ctypes is creating C functions at runtime.  If you're
interested, the source is here:

There is additional state. On Windows, the function AllocCallback() does
the trick.  It uses CallbackTemplate(), which is a small inline
assembler function template, which is copied into malloc'ed memory, and
then some dwords are filled out with the required state. This includes a
pointer to the Python callable.

For other systems, libffi does the trick.


More information about the Python-list mailing list