nogil and custom exception handler

315 views
Skip to first unread message

houbaastef .

unread,
Aug 11, 2015, 7:23:10 PM8/11/15
to cython...@googlegroups.com
Hello,

i'm wrapping a C++ API.

The C++ calls can block for several seconds, so it's a good opportunity for nogil. Thus I declare the API with :
cdef extern from "blabla.h" namespace "NS" nogil
The API uses a bunch of specific C++ exceptions that inherit from std::runtime_error.

So i mapped the C++ exceptions to Python exceptions using a custom handler:

-----------
custom_exception_handler.cpp:
extern PyObject *py_option_not_found;
void custom_exception_handler() {
// Catch a handful of different errors here and turn them into the
// equivalent Python errors.
try {
if (PyErr_Occurred())
; // let the latest Python exn pass through and ignore the current one
else
throw;
} catch (const NS::option_not_found& exn) {
PyErr_SetString(py_option_not_found, exn.what());
...
--------------
cython exceptions in pxd/pyx:
cdef public PyObject* py_option_not_found   (pxd)

class OptionNotFound(ValueError): (pyx)
"""
Exception thrown when an option is not found.
"""
cdef public PyObject* py_option_not_found = <PyObject*>OptionNotFound
--------------------
The handler is declared like in cython:

cdef extern from "custom_exception_handler.h" namespace "NS":
cdef void custom_exception_handler()
--------------------
and used like in cython:
cdef extern from "blabla.h" namespace "NS" nogil:
cdef cppclass RAW:
RAW(const string &data) except +custom_exception_handler


All is fine... But i wondered if the nogil statement will get along nicely with the "except+". custom_exception_handler clearly uses Python objects. So shoud I acquire the GIL back in custom_exception_handler ? Or cython just gently takes care of it ?

Thanks,
Stephane


Ian Henriksen

unread,
Aug 11, 2015, 7:34:05 PM8/11/15
to cython-users
Good question. This was fixed some time ago in https://github.com/cython/cython/commit/6795a2ba4761110c64c7a36401cb676614ba9f79.
If it needs to, Cython acquires the gil in the catch statement that calls the exception handling function.
Cheers,
-Ian Henriksen

houbaastef .

unread,
Aug 11, 2015, 8:09:59 PM8/11/15
to cython...@googlegroups.com
Good to know :) Thanks

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages