在Cython中处理自定义C++异常

And*_*ler 6 c++ exception-handling cython

从Cython调用时,我在处理自定义C++异常时遇到一些麻烦.我的情况如下:我有一个CustomLibraryException用于所有异常的库.我想要的是基本上得到错误消息并用它引发Python错误.

用户指南有一些线索,但它是有点非特异性.第一种可能性是:

cdef int bar()除了+ ValueError

这会将CustomLibraryExceptiona 转换为a ValueError,但会丢失错误消息.

另一种可能性是使用明确转换错误

cdef int raise_py_error()
cdef int something_dangerous() except +raise_py_error
Run Code Online (Sandbox Code Playgroud)

我真的不明白这个解决方案.我知道raise_py_error必须是一个以某种方式处理错误的C++函数.我不知道如何处理它.该函数没有获得参数,并catch在C++中的块内调用.

如果任何人有一个在Cython中处理C++异常的工作示例,那将会有很大的帮助.

FDS*_*FDS 7

同意文档页面中的措辞留下了一些不足之处.虽然" Cython不能抛出C++异常 ",但这里有一个raise_py_error可以满足我们的需求.

首先,在cython中定义自定义异常类,并使用"public"关键字对其进行处理

from cpython.ref cimport PyObject

class JMapError(RuntimeError):
  pass

cdef public PyObject* jmaperror = <PyObject*>JMapError
Run Code Online (Sandbox Code Playgroud)

然后编写异常处理程序(文档不是很清楚,这必须用C++编写并导入):

#include "Python.h"
#include "jmap/cy_utils.H"
#include "jmap/errors.H"
#include <exception>
#include <string>

using namespace std;

extern PyObject *jmaperror;

void raise_py_error()
{
  try {
    throw;
  } catch (JMapError& e) {
    string msg = ::to_string(e.code()) +" "+ e.what();
    PyErr_SetString(jmaperror, msg.c_str());
  } catch (const std::exception& e) {
    PyErr_SetString(PyExc_RuntimeError, e.what() );
  }
}
Run Code Online (Sandbox Code Playgroud)

最后,使用extern块将处理程序带入cython,并使用它:

cdef extern from "jmap/cy_utils.H":
  cdef void raise_py_error()

void _connect "connect"() except +raise_py_error
Run Code Online (Sandbox Code Playgroud)

完成.我现在看到新的异常,使用错误代码构建:

JMapError: 520 timed connect failed: Connection refused
Run Code Online (Sandbox Code Playgroud)


bfr*_*hle 5

Cython 中的默认 C++ 异常处理程序应该准确说明如何完成您想要执行的操作:

static void __Pyx_CppExn2PyErr() {
  // 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 std::bad_alloc& exn) {
    PyErr_SetString(PyExc_MemoryError, exn.what());
  } catch (const std::bad_cast& exn) {
    PyErr_SetString(PyExc_TypeError, exn.what());
  } catch (const std::domain_error& exn) {
    PyErr_SetString(PyExc_ValueError, exn.what());
  } catch (const std::invalid_argument& exn) {
    PyErr_SetString(PyExc_ValueError, exn.what());
  } catch (const std::ios_base::failure& exn) {
    // Unfortunately, in standard C++ we have no way of distinguishing EOF
    // from other errors here; be careful with the exception mask
    PyErr_SetString(PyExc_IOError, exn.what());
  } catch (const std::out_of_range& exn) {
    // Change out_of_range to IndexError
    PyErr_SetString(PyExc_IndexError, exn.what());
  } catch (const std::overflow_error& exn) {
    PyErr_SetString(PyExc_OverflowError, exn.what());
  } catch (const std::range_error& exn) {
    PyErr_SetString(PyExc_ArithmeticError, exn.what());
  } catch (const std::underflow_error& exn) {
    PyErr_SetString(PyExc_ArithmeticError, exn.what());
  } catch (const std::exception& exn) {
    PyErr_SetString(PyExc_RuntimeError, exn.what());
  }
  catch (...)
  {
    PyErr_SetString(PyExc_RuntimeError, "Unknown exception");
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以#define __Pyx_CppExn2PyErr your_custom_exn_handler在包含的 .h 文件中覆盖通用行为,或者使用一次性自定义处理程序作为

cdef extern from "...":
    void your_exn_throwing_fcn() except +your_custom_exn_handler
Run Code Online (Sandbox Code Playgroud)


Fre*_*Foo 2

如果CustomLibraryException派生自std::runtime_error(作为行为良好的 C++ 异常应该),那么您看到的行为是 Cython 中的错误。

如果没有,那么最简单的方法是将您正在调用的 C++ 函数包装在转换异常的 C++ 辅助函数中:

double foo(char const *, Bla const &);  // this is the one we're wrapping

double foo_that_throws_runtime_error(char const *str, Bla const &blaref)
{
    try {
        return foo(str, blaref);
    } catch (CustomLibraryException const &e) {
        throw std::runtime_error(e.get_the_message());
    }
}
Run Code Online (Sandbox Code Playgroud)

这将导致RuntimeErrorPython 端引发 a 。或者,throwanstd::invalid_argumentraiseaValueError等(请参阅您链接到的页面中的表格)。