2012-08-29 10 views
5

Tengo un caso más simple prueba aquí:TRAGO se estrella Python

%module test 
%{ 

static char* MyExceptionName = "_test.MyException"; 
static PyObject* MyException = NULL; 

%} 

%inline %{ 

static PyObject* Foo() 
{ 
    PyErr_SetNone(MyException); 
    return NULL; 
} 

%} 

%init 
{ 
    MyException = PyErr_NewException(MyExceptionName, NULL, NULL); 
} 

Aquí está la secuencia de comandos setup.py:

from distutils.core import setup, Extension 
setup(name="test", version="1.0", 
    ext_modules = [Extension("_test", ["test_wrap.c"])]) 

Cuando construyo y probarlo de la siguiente manera, me sale:

swig -python -threads test.i 
python_d -c "import test; test.Foo()" 
Fatal Python error: PyThreadState_Get: no current thread 

El rastreo que me dieron fue

python27_d.dll!Py_FatalError(const char * msg=0x000000001e355a00) Line 1677 C 
python27_d.dll!PyThreadState_Get() Line 330 C 
python27_d.dll!PyErr_Restore(_object * type=0x00000000020d50b8, _object * value=0x0000000000000000, _object * traceback=0x0000000000000000) Line 27 + 0x5 bytes C 
python27_d.dll!PyErr_SetObject(_object * exception=0x00000000020d50b8, _object * value=0x0000000000000000) Line 58 C 
python27_d.dll!PyErr_SetNone(_object * exception=0x00000000020d50b8) Line 64 C 
_test_d.pyd!Foo() Line 2976 C 

Medio Ambiente:

  • Win 7 64 bits,
  • Python 2.7.3 (por defecto, Aug 15 2012, 18:18:52) [64 bit MSC v.1500 (AMD64)] en Win32
  • trago 2.0.7

Respuesta

3

el motivo del error, como resulta que es porque cuando -threads se habilita a través de

swig -threads -python test.i 

obtenemos algo como esto (el exceso de código ha sido redactada):

PyObject *_wrap_Foo(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { 
    PyObject *resultobj = 0; 
    PyObject *result = 0 ; 

    if (!PyArg_ParseTuple(args,(char *)":Foo")) SWIG_fail; 
    { 
    SWIG_PYTHON_THREAD_BEGIN_ALLOW; 
    result = (PyObject *)Foo(); 
    SWIG_PYTHON_THREAD_END_ALLOW; 
    } 
    resultobj = result; 
    return resultobj; 
fail: 
    return NULL; 
} 

static PyObject* Foo() 
{ 
    PyErr_SetNone(MyException); 
    return NULL; 
} 

ve, cuando se llama Foo(), el bloqueo del intérprete global ya ha sido puesto en libertad. Foo() ya no debería hacer ninguna llamada a la API de Python.

La solución es usar SWIG_Python_SetErrorObj, que toma el bloqueo de Intérprete global antes de llamar a Python C API.

static PyObject* Foo() 
{ 
    SWIG_Python_SetErrorObj(MyException, Py_None); 
    return NULL; 
} 

Otro método es usar SWIG_PYTHON_THREAD_BEGIN_BLOCK; y SWIG_PYTHON_THREAD_END_BLOCK;

static PyObject* Foo() 
{ 
    SWIG_PYTHON_THREAD_BEGIN_BLOCK; 

    PyErr_SetNone(MyException); 

    SWIG_PYTHON_THREAD_END_BLOCK; 
    return NULL; 
} 
Cuestiones relacionadas