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

时间:2012-11-01 20:47:35

标签: 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" ) );
}

并在正确包装函数后从Cython中获取:

try:
    loadFile(myfilename)
except RuntimeError:
    print "Can't load file"

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

2 个答案:

答案 0 :(得分:2)

您是否使用extern声明异常处理?您应该阅读有关C ++异常处理的内容:http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#exceptions

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

cdef extern from "some_file.h":
    cdef int foo() except +

答案 1 :(得分:1)