python - PyErr_SetString 不会立即引发异常(Swig)?

标签 python c swig

我正在使用 SWIG 将 C 库包装到 python 模块。但是似乎没有在正确的地方引发异常,我有一个简单的演示,

except_test.i

%module except_test


%{
#include "except_test.h"
#include <stdio.h>
%}

%{
static int flagged_exception = 0;

void throw_except()
{
    flagged_exception = 1;
    printf("flag set \n");
}
%}

%exception {
    $action
    printf("exception block\n");
    if (flagged_exception) {
        printf("before setstring\n");
        PyErr_SetString(PyExc_RuntimeError, "test except");
        printf("after setstring\n");
        flagged_exception = 0;
    }
}
%include "except_test.h"

except_test.c

#include "except_test.h"


int except_test(int a) {

    if (a < 0) {
        throw_except();
        return 0;
    } else{
        return -1;
    }
}

run_except.py

from except_test import *
import time

def test():
    b = except_test(-1)
    print 'b=', b

try:
    test()
except:
    print "caught exception"

for i in range(10):
    print i
    time.sleep(1)

现在如果我运行 run_except.py

$python run_except.py 
flag set 
exception block
before setstring
after setstring
b= 0
0
Traceback (most recent call last):
  File "run_except.py", line 15, in <module>
    time.sleep(1)
RuntimeError: test except

如输出所示,try/catch block 没有捕获异常。 为什么是这样?以及如何避免这种情况?

谢谢,

最佳答案

您必须从 Python 扩展返回 NULL 以使其立即注意到错误:

if (flagged_exception) {
    PyErr_SetString(PyExc_RuntimeError, "test except");
    flagged_exception = 0;
    return NULL;
}

但是使用通用的 SWIG 宏将使 SWIG 接口(interface)对其他语言的移植性更强。

关于python - PyErr_SetString 不会立即引发异常(Swig)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20711606/

相关文章:

python - 如何在使用 Python 进行网页抓取时绕过 cookie 协议(protocol)页面?

python - oct2py 没有看到 OCTAVE_EXECUTABLE 环境变量 (Windows)

python - 如何使用 python 获取两个日期时间(PDT 格式)之间的秒数差异?

c - 为什么“while(!feof(file))”总是错误的?

c - C程序不执行main之外的函数

c - 窗口服务: get each users' %APPDATA% variable

python - SWIG - python 中的 C++ 代码

python - 在 OSX 下使用 SWIG 时出现致命的 Python 错误

python - SWIG/Python : Passing pointer into function

修改环境的 Python 子进程/Popen