使用SWIG动态地将自定义C++异常重新抛出为Python异常

tba*_*ker 22 c++ python reflection swig exception

情况

我想使用SWIG为C++ API创建一个Python语言绑定.某些API函数可能会抛出异常.C++应用程序具有自定义异常的层次结构,如下例所示:

std::exception
  -> API::Exception
    -> API::NetworkException
      -> API::TimeoutException
      -> API::UnreachableException
    -> API::InvalidAddressException
Run Code Online (Sandbox Code Playgroud)

期望的行为如下:

  1. 所有异常类型都应该具有匹配的Python类作为包装器.这些包装类应该是有效的Python异常.

  2. 当API调用抛出C++异常时,应该捕获它.的相应Python异常(即包装类被捕捉的C++异常的)应被抛出.

  3. 这应该是一个动态过程:Python 异常类型在运行时决定,仅基于捕获的C++异常的运行时类型.这样,就不需要在SWIG接口文件中描述完整的异常层次结构.

问题和疑问

  1. 包装类不是Python异常.

    虽然SWIG为所有自定义异常(如任何其他类)创建包装类,但这些类不是Python异常.基本异常的包装器(API::Exception在示例中)扩展Object而不是BaseExceptionPython类,其中应该派生Python中的所有异常.

    此外,似乎不允许SWIG手动添加父类.请注意,通过使用SWIG与Java一起使用时可以这样做%typemap(javabase)(有关详细信息,请参阅SWIG文档).

  2. Python C API如何抛出用户定义的异常?

    从Python C API抛出Python异常的最常见方法是调用PyErr_SetString [reference].这也显示在下面的演示应用程序中.

    但这对于Python的标准(内置)异常来说是微不足道的,因为对它们的引用存储在Python C API 中的全局变量[ reference ]中.

    我知道有一个方法PyErr_NewException [引用]来获取对自定义异常的引用,但我没有得到这个工作.

  3. Python C API如何在运行时评估C++类型,然后按名称查找相应的Python包装类?

    我假设可以通过Python C API 的反射部分在运行时按名称搜索Python类.这是要走的路吗?它是如何在实践中完成的?

演示应用程序

为了试验这个问题,我创建了一个带有单个函数的小型C++ API,用于计算数字的阶乘.它具有最小的自定义异常层次结构,仅包含一个类TooBigException.

请注意,此异常充当一般问题中的基本异常,并且应用程序应该与其的任何子类一起使用.这意味着解决方案可能只使用捕获的异常的动态(即运行时)类型在Python中重新抛出它(见下文).

演示应用程序的完整源代码如下:

// File: numbers.h
namespace numbers {
int fact(int n);
}

// File: numbers.cpp
#include "TooBigException.h"
namespace numbers {
int fact(int n) {
    if (n > 10) throw TooBigException("Value too big", n);
    else if (n <= 1) return 1;
    else return n*fact(n-1);
}
}

// File: TooBigException.h
namespace numbers {
class TooBigException: public std::exception {
public:
    explicit TooBigException(const std::string & inMessage,
                             const int inValue);
    virtual ~TooBigException() throw() {}
    virtual const char* what() const throw();
    const std::string & message() const;
    const int value() const;
private:
    std::string mMessage;
    int mValue;
};
}

// File: TooBigException.cpp
#include "TooBigException.h"
namespace numbers {
TooBigException::TooBigException(const std::string & inMessage, const int inValue):
    std::exception(),
    mMessage(inMessage),
    mValue(inValue)
{
}
const char* TooBigException::what() const throw(){
    return mMessage.c_str();
}
const std::string & TooBigException::message() const {
    return mMessage;
}
const int TooBigException::value() const {
    return mValue;
}
}
Run Code Online (Sandbox Code Playgroud)

要获取Python绑定,我使用以下SWIG接口文件:

// File: numbers.i
%module numbers
%include "stl.i"
%include "exception.i"

%{
#define SWIG_FILE_WITH_INIT
#include "TooBigException.h"
#include "numbers.h"
%}

%exception {
    try {
        $action
    }
    catch (const numbers::TooBigException & e) {
        // This catches any self-defined exception in the exception hierarchy,
        // because they all derive from this base class. 
        <TODO>
    }
    catch (const std::exception & e)
    {
        SWIG_exception(SWIG_RuntimeError, (std::string("C++ std::exception: ") + e.what()).c_str());
    }
    catch (...)
    {
        SWIG_exception(SWIG_UnknownError, "C++ anonymous exception");
    }
}

%include "TooBigException.h"
%include "numbers.h"
Run Code Online (Sandbox Code Playgroud)

因此,每次调用API都会被try-catch块包装.捕获并处理我们的基本类型的第一个例外.然后使用SWIG异常库捕获并重新抛出所有其他异常.

注意numbers::TooBigException抓住任何子类,并且应该抛出它们的动态(即运行时)类型的包装,而不是它们的静态(即编译时)类型的包装,它总是TooBigException!

通过在Linux机器上执行以下命令,可以轻松构建项目:

$ swig -c++ -python numbers.i
$ g++ -fPIC -shared TooBigException.cpp numbers.cpp numbers_wrap.cxx \
    -I/usr/include/python2.7 -o _numbers.so
Run Code Online (Sandbox Code Playgroud)

目前的实施

我当前的实现仍然(成功)抛出固定的标准Python异常.<TODO>然后将上面的代码替换为:

PyErr_SetString(PyExc_Exception, (std::string("C++ self-defined exception ") + e.what()).c_str());
return NULL;
Run Code Online (Sandbox Code Playgroud)

这给出了Python中的以下(预期)行为:

>>> import numbers
>>> fact(11)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: C++ self-defined exception Value too big
Run Code Online (Sandbox Code Playgroud)

Mar*_*vin 9

看起来有人在swig-user列表中回答了你的基本问题......

%exception {
  try {
    $action
  } catch (MyException &_e) {
    SWIG_Python_Raise(SWIG_NewPointerObj(
            (new MyException(static_cast<const MyException& >(_e))),  
            SWIGTYPE_p_MyException,SWIG_POINTER_OWN),
        "MyException", SWIGTYPE_p_MyException); 
    SWIG_fail;
  } 
}
Run Code Online (Sandbox Code Playgroud)

我相信这确实假设你已经为你的异常类生成了包装器.


Evg*_*yuk 5

层次结构的示例

std::exception
  -> API::Exception
    -> API::NetworkException
      -> API::TimeoutException
      -> API::UnreachableException
    -> API::InvalidAddressException
Run Code Online (Sandbox Code Playgroud)

example.i:

%module example
%include "stl.i"
%include "exception.i"

%{
#define SWIG_FILE_WITH_INIT
#include "example.cpp"
%}

%{

#define CATCH_PE(Namespace,Exception) \
    catch(const Namespace::Exception &e) \
    { \
       SWIG_Python_Raise(SWIG_NewPointerObj(new Namespace::Exception(e), \
            SWIGTYPE_p_##Namespace##__##Exception,SWIG_POINTER_OWN), \
            #Exception, SWIGTYPE_p_##Namespace##__##Exception); \
       SWIG_fail; \
    } \
/**/

// should be in "derived first" order
#define FOR_EACH_EXCEPTION(ACTION) \
   ACTION(API,UnreachableException) \
   ACTION(API,TimeoutException) \
   ACTION(API,InvalidAddressException) \
   ACTION(API,NetworkException) \
   ACTION(API,Exception) \
/**/
// In order to remove macros, need traits:
// http://swig.10945.n7.nabble.com/traits-based-access-to-swig-type-info-td12315.html
%}

%exception {
    try {
        $action
    }
    FOR_EACH_EXCEPTION(CATCH_PE)
    catch (const std::exception & e)
    {
        SWIG_exception(SWIG_RuntimeError, (std::string("C++ std::exception: ") + e.what()).c_str());
    }
    catch (...)
    {
        SWIG_exception(SWIG_UnknownError, "C++ anonymous exception");
    }
}

%include "example.cpp"
Run Code Online (Sandbox Code Playgroud)

example.cpp:

#include <exception>
#include <stdexcept>

namespace API
{
    struct Exception: std::exception
    {
        virtual const char* what() const throw()
        {
            return "It is API::Exception";
        }
    };
    struct NetworkException: Exception
    {
        virtual const char* what() const throw()
        {
            return "It is API::NetworkException";
        }
    };
    struct TimeoutException: NetworkException
    {
        virtual const char* what() const throw()
        {
            return "It is API::TimeoutException";
        }
    };
    struct UnreachableException: NetworkException
    {
        virtual const char* what() const throw()
        {
            return "It is API::UnreachableException";
        }
    };
    struct InvalidAddressException: Exception
    {
        virtual const char* what() const throw()
        {
            return "It is API::InvalidAddressException";
        }
    };

    inline void select(int i)
    {
        switch(i)
        {
            case 0: throw Exception();
            case 1: throw NetworkException();
            case 2: throw TimeoutException();
            case 3: throw UnreachableException();
            case 4: throw InvalidAddressException();
            default: throw std::runtime_error("It is std::runtime_error");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

建立:

swig -c++ -python example.i &&
g++ -fPIC -shared -lpython2.7 example.cpp example_wrap.cxx -I/usr/include/python2.7 -o _example.so
Run Code Online (Sandbox Code Playgroud)

test.py:

#!/usr/bin/env python2.7

from exceptions import BaseException
from example import *

def catch(i):
    try:
        select(i)
    except UnreachableException as e:
        print "Caught UnreachableException"
        print e.what()
        print e
    except TimeoutException as e:
        print "Caught TimeoutException"
        print e.what()
        print e
    except InvalidAddressException as e:
        print "Caught InvalidAddressException"
        print e.what()
        print e
    except NetworkException as e:
        print "Caught NetworkException"
        print e.what()
        print e
    except Exception as e:
        print "Caught Exception"
        print e.what()
        print e
    except BaseException as e:
        print "Caught BaseException"
        print str(e)
    print "_"*16

for i in xrange(6):
    catch(i)
Run Code Online (Sandbox Code Playgroud)

输出是:

Caught Exception
It is API::Exception
<example.Exception; proxy of <Swig Object of type 'API::Exception *' at 0x7f9f54a02120> >
________________
Caught NetworkException
It is API::NetworkException
<example.NetworkException; proxy of <Swig Object of type 'API::NetworkException *' at 0x7f9f54a02120> >
________________
Caught TimeoutException
It is API::TimeoutException
<example.TimeoutException; proxy of <Swig Object of type 'API::TimeoutException *' at 0x7f9f54a02120> >
________________
Caught UnreachableException
It is API::UnreachableException
<example.UnreachableException; proxy of <Swig Object of type 'API::UnreachableException *' at 0x7f9f54a02120> >
________________
Caught InvalidAddressException
It is API::InvalidAddressException
<example.InvalidAddressException; proxy of <Swig Object of type 'API::InvalidAddressException *' at 0x7f9f54a02120> >
________________
Caught BaseException
C++ std::exception: It is std::runtime_error
________________
Run Code Online (Sandbox Code Playgroud)

基于maillist的回答.