2010-08-09 50 views
2

我正在創建一個python c擴展,但在查找我想要做的文檔時遇到困難。我基本上想創建一個指向cstruct的指針,並能夠訪問該指針。示例代碼如下。任何幫助,將不勝感激。訪問PyObject的底層結構

typedef struct{ 
int x; 
int y; 
} Point; 

typedef struct { 
PyObject_HEAD 
Point* my_point; 
} PointObject; 

static PyTypeObject PointType = { 
    PyObject_HEAD_INIT(NULL) 
    0,       /*ob_size*/ 
    "point",    /*tp_name*/ 
    sizeof(PointObject), /*tp_basicsize*/ 
    0,       /*tp_itemsize*/ 
    0,       /*tp_dealloc*/ 
    0,       /*tp_print*/ 
    0,       /*tp_getattr*/ 
    0,       /*tp_setattr*/ 
    0,       /*tp_compare*/ 
    0,       /*tp_repr*/ 
    0,       /*tp_as_number*/ 
    0,       /*tp_as_sequence*/ 
    0,       /*tp_as_mapping*/ 
    0,       /*tp_hash */ 
    0,       /*tp_call*/ 
    0,       /*tp_str*/ 
    0,       /*tp_getattro*/ 
    0,       /*tp_setattro*/ 
    0,       /*tp_as_buffer*/ 
    Py_TPFLAGS_DEFAULT,  /*tp_flags*/ 
    "point objects",   /* tp_doc */ 
}; 

static PyObject* set_point(PyObject* self, PyObject* args) 
{ 
PyObject* point; 

if (!PyArg_ParseTuple(args, "O", &point)) 
{ 
    return NULL; 
} 

    //code to access my_point  
} 

回答

3

PyArg_ParseTuple不應使用格式OO!(見文檔):

O! (object) [typeobject, PyObject *] 

存放在C對象 指針Python對象。這與O類似,但 需要兩個C參數:第一個是 Python類型對象的地址, 第二個是存儲對象指針的變量(類型PyObject *)到 的變量的地址( ) 。如果 Python對象沒有所需的類型 ,則引發TypeError。

一旦你做到了這一點,你知道,在你的函數體(PointObject*)point將是一個正確的和有效的指針PointObject,因此,其->my_point將是Point*你所追求的。使用普通格式O,您必須自己檢查類型。

編輯:在註釋OP詢問源...:

static PyObject* 
set_point(PyObject* self, PyObject* args) 
{ 
    PyObject* point; 

    if (!PyArg_ParseTuple(args, "O!", &PointType, &point)) 
    { 
     return NULL; 
    } 

    Point* pp = ((PointObject*)point)->my_point; 

    // ... use pp as the pointer to Point you were looking for... 

    // ... and incidentally don't forget to return a properly incref'd 
    // PyObject*, of course;-) 
} 
+0

亞歷克斯,我能得到我還是有點失落了如何做到這一點的來源。 – Pat 2010-08-09 01:23:31

+0

OK,@user,我剛剛編輯我的A,以便根據您的要求添加源代碼。 – 2010-08-09 01:31:58