2013-12-20 1 views
2

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하지 않았다. 이유가 무엇인가요? 어떻게 이것을 피하는가?

덕분에,

+0

_wrap.c 파일에서 생성 된 코드를 확인하십시오. % 예외가있는 코드입니까? – Schollii

답변

3

당신은 즉시 오류를 통지하도록 파이썬 확장에서 NULL을 반환해야 :

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

그러나 다른 언어로 꿀꺽 꿀꺽 인터페이스는 더 휴대용 만들 것입니다 일반 꿀꺽 꿀꺽 매크로를 사용하여.

2

당신이 바로 PyErr_SetStringSWIG_fail;을 넣어해야합니다. 또는 편리하고 (더 중요한 언어 독립적 인) 매크로 SWIG_exception(SWIG_RuntimeError, "error message")PyErr_SetStringSWIG_fail을 래핑합니다.

관련 문제