Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why PyObject* can point to any object in python?

Tags:

python

c

In python's source code, there are some macro definitions like this:

#define PyObject_HEAD    \
    int ob_refcnt;       \
    struct _typeobject *ob_type;


#define PyObject_VAR_HEAD  \
    PyObject_HEAD          \
    int ob_size; 


typedef struct _object {  
    PyObject_HEAD  
} PyObject;    

typedef struct _object {  
    PyObject_HEAD   
    long ob_ival;   
} PyIntObject;   

typedef struct {   
    PyObject_VAR_HEAD   
} PyVarObject;   

The question is, why PyObject* can point to each object(such as PyIntObject, PyVarObject) in python?

like image 521
米雪儿 Avatar asked Jul 31 '12 09:07

米雪儿


1 Answers

Each struct for the different types of Python object has an instance of PyObject_HEAD as its first member (or the first member of its first member, and so on).

This member sub-object is guaranteed to be located at the same address as the full object.

The PyObject_HEAD* points at that member sub-object, but could be cast to the full type once ob_type has been inspected to work out what the full type is.

This trick isn't unique to CPython -- it's often used to implement a limited kind of inheritance in C. Basically you model the "is a X" relationship by "has a X at the start of".

like image 187
Steve Jessop Avatar answered Oct 11 '22 13:10

Steve Jessop