SWIG를 사용하여 파이썬 모듈에 C lib를 래핑합니다. 그러나 예외가 올바른 위치에 제기하지 않는 것,이에 대한 간단한 데모,PyErr_SetString은 즉시 예외를 발생시키지 않습니다 (Swig)?
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)
가 지금은 출력 쇼 등
$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
run_except.py 실행할 경우 try/catch 블록은 예외를 catch하지 않았다. 이유가 무엇인가요? 어떻게 이것을 피하는가?
덕분에,
_wrap.c 파일에서 생성 된 코드를 확인하십시오. % 예외가있는 코드입니까? – Schollii