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

后端 未结 6 1214
天涯浪人
天涯浪人 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:15

    U can also use:

    catches: http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_catches

    Example:

    %catches(std::exception, std::string, int, ...);
    

    which generates for each function a try catch block:

      try {
        result = (namespace::Function *)new namespace::Function ((uint16_t const *)arg1);
      }
      catch(std::exception &_e) {
        SWIG_exception_fail(SWIG_SystemError, (&_e)->what());
      }
      catch(std::string &_e) {
        SWIG_Python_Raise(SWIG_From_std_string(static_cast< std::string >(_e)), "std::string", 0); SWIG_fail;
      }
      catch(int &_e) {
        SWIG_Python_Raise(SWIG_From_int(static_cast< int >(_e)), "int", 0); SWIG_fail;
      }
      catch(...) {
        SWIG_exception_fail(SWIG_RuntimeError,"unknown exception");
      }
    

提交回复
热议问题