Accessing the underlying struct of a PyObject

跟風遠走 提交于 2019-11-28 22:10:32

Your PyArg_ParseTuple should not use format O but O! (see the docs):

O! (object) [typeobject, PyObject *]

Store a Python object in a C object pointer. This is similar to O, but takes two C arguments: the first is the address of a Python type object, the second is the address of the C variable (of type PyObject*) into which the object pointer is stored. If the Python object does not have the required type, TypeError is raised.

Once you've done that, you know that in your function's body (PointObject*)point will be a correct and valid pointer to a PointObject, and therefore its ->my_point will be the Point* you seek. With a plain format O you'd have to do the type checking yourself.

Edit: the OP in a comments asks for the source...:

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;-)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!