2014-10-24 3 views
2

나는 라즈베리 파이를위한 특정 하드웨어 쉴드를 사용할 수있는 파이썬 (3.x) 용 C++ 확장을 작성하려고합니다.
C 및/또는 C++을 작성한 경험이 없지만 실제로 파이썬 웹 사이트의 설명서를 사용하면 실제로 작동합니다. 내가 뭘하고 싶은지 내 유형을 싱글 톤으로 만들지 만 init 메소드가 에러 (-1)를 반환하면 생성자에 대한 두 번째 호출이 상황을 망칠 것이다. init이 오류없이 반환되면 실제로 예상대로 작동합니다. 내 코드의파이썬 C++ 확장 싱글 톤

중요한 부분 :

static PyObject * 
MyType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) 
{ 
    static MyType *self = NULL; /* static to create a Singleton */ 

    if (self == NULL) { 
     self = (MyType *)type->tp_alloc(type, 0); 

     self->is_initialized = false; 
    } 
    else { 
     Py_XINCREF(self); 
    } 

    return (PyObject *)self; 
} 

static int 
MyType_init(MyType *self, PyObject *args, PyObject *kwds) 
{ 
    const char *i2c_addr; 

    self->rpi_model = RPI_MODEL_B; 
    self->enabled_components = COMPONENTS_ALL_BIT; 

    static char *kwlist[] = {"rpi_model", "enabled_components", NULL}; 

    if (self != NULL && !self->is_initialized) { 
     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii", kwlist, &self->rpi_model, &self->enabled_components)) { 

      return -1; 
     } 
    } 

    /* 
     DO SOME INITIALIZATION STUFF 
    */ 

    if (!self->component_A->testConnection()) { 
     PyErr_SetString(InitializationException, "Unable to communicate with component_A."); 
     return -1; 
    } 

    self->is_initialized = true; 
    return 0; 
} 

나는 또한 tp_dealloc 멤버 다음 연료 소모량 설치 :

static void 
MyType_dealloc(PyObject *self) 
{ 
    Py_TYPE(self)->tp_free((PyObject*)self); 
} 

내가 (디버깅을 위해) 이러한 방법에 일부 인쇄 문을 넣어 및 MyType_new에 대한 두 번째 호출에서 self != NULL이 나타나지만 초기화 실패시 MyType_dealloc 메서드가 실행되었습니다.

아무도 올바른 방향으로 나를 가리킬 수 있습니까?

답변

0

MyType_deallocself이 (가) NULL으로 설정되어 있지 않습니다.

또한 __new____init__을 모두 가질 필요가 없습니다. 모두 __new__에 넣으세요.