【问题标题】:%exception got ignored by SWIG(python) wrapper?SWIG(python)包装器忽略了%异常?
【发布时间】:2013-12-20 09:27:39
【问题描述】:

我正在尝试使用 SWIG 将 C lib 包装到 python mod,但我无法让异常正常工作。这是代码的一个小例子,

except_test.i

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

%include "except_test.h"

%{
static int flagged_exception = 0;

void throw_except()
{
    flagged_exception = 1;
}
%}

%exception {
    $action
    if (flagged_exception) {
        PyErr_SetString(PyExc_RuntimeError, "test except");
        flagged_exception = 0;
    }
}

except_test.c:

int except_test(int a) {

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

然后当我运行 except_test() 函数时,没有抛出异常

run_except.py

from except_test import *

b = except_test(-1)
print 'b=', b

运行:

$ python run_except.py 
b= 0
$

这里有什么问题?

【问题讨论】:

  • throw 语句在哪里?另请注意,C 没有异常。

标签: python c swig


【解决方案1】:

在处理except_test.h标头之前声明%exception;否则,当函数包装在 SWIG 中时,它不会处于活动状态:

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

%exception {
    $action
    if (flagged_exception) {
        PyErr_SetString(PyExc_RuntimeError, "test except");
        flagged_exception = 0;
        return NULL; // ** need to add this **
    }
}

%include "except_test.h"

%{
static int flagged_exception = 0;

void throw_except()
{
    flagged_exception = 1;
}
%}

结果:

>>> import except_test
>>> except_test.except_test(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: test except

【讨论】:

  • 谢谢,成功了!但是现在我有另一个问题,看起来异常不会在 PyErr_SetString() 之后立即发生。如果我在 run_except.py 中的 except_test() 调用之后有一些代码,就会抛出异常,这使得在 python 脚本中很难捕获异常。你碰巧知道为什么吗?也许我应该开始另一个问题。
  • 设置错误字符串后需要返回NULL。由于忘记了这一点,它可能会延迟,并且稍后会出现在代码中。请参阅上面的更新。如果您在我更新它之前注意到我的结果输出,那么由于缺少return NULL,在抛出异常之前打印了由except_test 返回的0。现在它不这样做了。
猜你喜欢
  • 2010-11-26
  • 1970-01-01
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
  • 2012-03-03
相关资源
最近更新 更多