访问PyObject的底层结构

我正在创建一个python c扩展,但很难找到我想做的文档。 我基本上想要创建一个指向cstruct的指针,并能够访问该指针。 示例代码如下。 任何帮助,将不胜感激。

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 } 

你的PyArg_ParseTuple不应该使用格式O而是O! (参见文档):

 O! (object) [typeobject, PyObject *] 

将Python对象存储在C对象指针中。 这与O类似,但需要两个C参数:第一个是Python类型对象的地址,第二个是存储对象指针的C变量(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;-) }