[Pyrex] Getting address of ob_type

Lenard Lindstrom len-l at telus.net
Sun Dec 31 06:55:49 UTC 2006


Nicholas Riley wrote:
> On Dec 29, 2006, at 1:50 PM, Lenard Lindstrom wrote:
>
>   
>> print (<PyObject *>o).ob_type.tp_name
>>     
>
> Thanks, it works.  I didn't realize you could cast a Python object  
> like that.  For completeness, this is what I used:
>
> cdef extern from "object.h":
>      ctypedef struct PyTypeObject:
>          char *tp_name
>      ctypedef struct PyObject:
>          PyTypeObject *ob_type
>
> cdef unsigned long type_addr(object object_):
>      return <unsigned long>&(<PyObject *>object_).ob_type
>
>   
I don't know if it is recommended, but it works in this case. It may be 
prohibited in future Pyrex versions. Just be sure to keep a reference to 
object_ while working on ob_type. The proper way would have been to use:

cdef extern form "object.h":
    class types.TypeType [object PyHeapTypeObject]:
        cdef char *tp_name

but a missing cast in the generated C code causes a compilation error 
because PyHeapTypeObject doesn't directly have ob_refcnt.

-- 
Lenard Lindstrom
<len-l at telus.net>





More information about the Pyrex mailing list