我使用SWIG将一个C-lib包装到python模块。但例外似乎并不是在正确的地方提出的,我有一个简单的演示
除了测试。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"
除测试c外
^{pr2}$快跑_除了.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)
如果我跑的话_除了.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块没有捕捉到异常。 为什么会这样?如何避免呢?在
谢谢
您需要将}和{}。在
SWIG_fail;
放在PyErr_SetString
之后。另外,还有一个方便的(更重要的是独立于语言的)宏SWIG_exception(SWIG_RuntimeError, "error message")
包装{您必须从Python扩展返回
NULL
,才能让它立即注意到错误:但是使用通用SWIG宏将使SWIG接口更易于移植到其他语言中。在
相关问题 更多 >
编程相关推荐