将c ++异常传播给cython - python异常

lin*_*llo 10 c++ python exception try-catch cython

我有一个Cython 0.17.1的问题

我的函数抛出一个std::runtime_error如果文件不存在,我想以某种方式将此异常传播到我的Cython代码.

void loadFile(const string &filename)
{
    // some code, if filename doesn't exists 
    throw std::runtime_error( std::string("File doesn't exists" ) );
}
Run Code Online (Sandbox Code Playgroud)

正确包装函数后从Cython:

try:
    loadFile(myfilename)
except RuntimeError:
    print "Can't load file"
Run Code Online (Sandbox Code Playgroud)

但是这个异常总是被忽略,我如何从Python中捕获c ++异常?

Rya*_*n P 5

你是在用 extern 声明异常处理吗?您应该阅读有关 C++ 异常处理的信息:http : //docs.cython.org/src/userguide/wrapping_CPlusPlus.html#exceptions

基本上,您需要执行以下操作:

cdef extern from "some_file.h":
    cdef int foo() except +
Run Code Online (Sandbox Code Playgroud)