[英]%exception got ignored by SWIG(python) wrapper?
I am trying to wrap a C lib to python mod with SWIG, but I am having trouble getting exceptions to work. 我正在尝试使用SWIG将C库包装为python mod,但是我无法使异常正常工作。 Here is a little example of the code,
这是代码的一个小例子,
except_test.i 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: except_test.c:
int except_test(int a) {
if (a < 0) {
throw_except();
return 0;
} else{
return -1;
}
}
Then when I ran the except_test() function, exception is not thrown 然后,当我运行exception_test()函数时,不会引发异常
run_except.py run_except.py
from except_test import *
b = except_test(-1)
print 'b=', b
run: 跑:
$ python run_except.py
b= 0
$
What is wrong here? 怎么了
Declare the %exception
before processing the except_test.h
header; 在处理
except_test.h
标头之前,声明%exception
; otherwise, it won't be active when the function is wrapped in SWIG: 否则,当将函数包装在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;
}
%}
Result: 结果:
>>> import except_test
>>> except_test.except_test(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: test except
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.