访问PyObject的基础结构

发布于 2021-01-29 17:17:50

我正在创建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    
}
关注者
0
被浏览
32
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    PyArg_ParseTuple不应该使用格式,O但是O!(请参阅文档):

    O! (object) [typeobject, PyObject *]
    

    将Python对象存储在C对象指针中。这类似于O,但是有两个C参数:第一个是Python类型对象的地址,第二个是对象指针存储在其中的C变量(PyObject
    *类型)的地址。如果Python对象没有所需的类型,则会引发TypeError。

    完成此操作后,您将知道在函数的主体(PointObject*)point中将是a的正确和有效指针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;-)
    }
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看