ctypes exception in callback handlind

Gordon groups at tolomea.com
Fri Nov 6 05:57:18 CET 2009


This post concerns the situation where Python code calls C code via
ctypes, the C code then calls a callback back into Python code which
in turn raises an exception.

Currently as I understand things when the callback finishes and
control is returning to C land ctypes will catch and print the
exception and then return normally back to C.
The standard way of doing something meaningful with the exception is
to catch it in the callback, set a global flag, somehow encourage the
C code to unwind back to the original Python call and there check the
flag and re-raise the exception.

My current problems involves a non recoverable error being raised in
the callback. The intermediate C code is not at all setup to deal with
a failure like this and I can't find a way to "somehow encourage the C
code to unwind".
For extra giggles I can't just hit sys.exit as this stack got invoked
as a callback out of a third party python library that needs to do
some clean up. All of which leaves me wishing that ctypes would
propgate the exception back to the python calling context for me.

One approach I can think of that I would like to get some feedback on
is the following:
Create a new ctypes calling convention that does a setjmp on entry.
When using that calling convention if an exception is raised by a call
back, catch it and store it somewhere, longjmp back to the setjmp
point and re-raise it.

I appreciate that this will generally leave the intervening C code in
an undefined state and as such would definitely have to be an optional
feature.

I realize that I could in theory do this myself by wrapping each of
the C calls with a wrapper that does the setjmp work, but there are
quite a few of them.

So any comments or suggestions?

G



More information about the Python-list mailing list