[PyQt] sip: extend exception support

Mathias.Born at gmx.de Mathias.Born at gmx.de
Wed Aug 15 14:54:11 BST 2012


Phil,

sip can already propagate C++ exceptions into Python in cases
where Python calls a C++ function which throws an exception.

However, if I extend a C++ class in Python and call a corresponding
(Python-)method in C++ via the wrapper, the sip generated
wrapper code checks for a Python exception, but doesn't throw an
excpetion itself.
For example:

========= <code generated by sip> =======================
boost::optional<int> sipVH_ltse_app_0(sip_gilstate_t sipGILState,PyObject *sipMethod,const std::string& a0)
{
    boost::optional<int> sipRes;
    PyObject *resObj = sipCallMethod(0,sipMethod,"N",new std::string(a0),sipType_std_string,NULL);

    if (!resObj || sipParseResult(0,sipMethod,resObj,"H5",sipType_boost_optional_1800,&sipRes) < 0)
        PyErr_Print();

    Py_XDECREF(resObj);
    Py_DECREF(sipMethod);

    SIP_RELEASE_GIL(sipGILState)

    return sipRes;
}
=========================================================

Here, "PyErr_Print" is called if the Python implementation of
the method raises an exception. This is fine for Qt which
cannot deal with exceptions, but in general I would find it
much more helpful if the wrapper code generated by sip
threw a C++ exception itself to signal the problem to the
caller.

Just define a class, e.g. "SIPPyException" (derived from
std::exception), which becomes part of the API and is always used
in such cases.
In order not to break existing code, it would only be used in
classes or methods which are annotated appropriately.
(So an additional annotation is necessary to activate this behavior.)

I believe an extension like this would make sip a lot more useful
for embedding Python into a C++ program.

Best Regards,
Mathias Born





More information about the PyQt mailing list