How do I propagate C++ exceptions to Python in a SWIG wrapper library?

后端 未结 6 1212
天涯浪人
天涯浪人 2020-12-13 04:54

I\'m writing a SWIG wrapper around a custom C++ library which defines its own C++ exception types. The library\'s exception types are richer and more specific than standard

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 05:23

    I'll add a bit here, since the example given here now says that "%except(python)" is deprecated...

    You can now (as of swig 1.3.40, anyhow) do totally generic, script-language-independent translation. My example would be:

    %exception { 
        try {
            $action
        } catch (myException &e) {
            std::string s("myModule error: "), s2(e.what());
            s = s + s2;
            SWIG_exception(SWIG_RuntimeError, s.c_str());
        } catch (myOtherException &e) {
            std::string s("otherModule error: "), s2(e.what());
            s = s + s2;
            SWIG_exception(SWIG_RuntimeError, s.c_str());
        } catch (...) {
            SWIG_exception(SWIG_RuntimeError, "unknown exception");
        }
    }
    

    This will generate a RuntimeError exception in any supported scripting language, including Python, without getting python specific stuff in your other headers.

    You need to put this before the calls that want this exception handling.

提交回复
热议问题