Pyr_SetString不立即引发异常(Swig)?

2024-09-28 22:25:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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块没有捕捉到异常。 为什么会这样?如何避免呢?在

谢谢


Tags: pytestincludetimeexceptionblockflagmodule
2条回答

您需要将SWIG_fail;放在PyErr_SetString之后。另外,还有一个方便的(更重要的是独立于语言的)宏SWIG_exception(SWIG_RuntimeError, "error message")包装{}和{}。在

您必须从Python扩展返回NULL,才能让它立即注意到错误:

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

但是使用通用SWIG宏将使SWIG接口更易于移植到其他语言中。在

相关问题 更多 >