我正在使用 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/