ctypes exception in callback handlind

G

Gordon

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top