[Pyrex] Getting address of ob_type

Lenard Lindstrom len-l at telus.net
Fri Dec 29 19:50:02 UTC 2006


Nicholas Riley wrote:
> Hi,
>
> I'm attempting to get the address of the ob_type field of a Python  
> object from Pyrex.  I tried the following:
>
> cdef extern from "object.h":
>      ctypedef struct PyTypeObject:
>          char *tp_name
>      ctypedef class __builtin__.object [object PyObject]:
>          cdef PyTypeObject *ob_type
>
> cdef unsigned long type_addr(object object_):
>      return <unsigned long>&object_.ob_type
>
> but I get back:
> /home/dcsfiles/njriley/Python/UFO/pyUFO.pyx:215:26: Cannot take  
> address of Python variable
>
> I've done something similar with a dict object, but I think the  
> problem is that "object" in the cdef is being interpreted as a  
> generic Python object (which it is, but...).  I also tried:
>
>      ctypedef class __builtin__.object as obj [object PyObject]:
>
> and
>
>     ctypedef class __builtin__.object [object PyObject] as obj:
>
> which look like they should fix it, but they don't work at all.
>
> Any ideas on how I can do this?
>
>   

# Access the ob_type field of an object.

cdef extern from "object.h":
    ctypedef struct PyTypeObject:
        char *tp_name
    ctypedef struct PyObject:
        PyTypeObject *ob_type

cdef object o
o = 12.0
print (<PyObject *>o).ob_type.tp_name


But unless you want to change an object's class use type(obj) or 
PyObject_Type instead.

cdef extern from "object.h":
    ctypedef struct PyTypeObject:
        char *tp_name

cdef object t
t = type(12.0)
print (<PyTypeObject *>t).tp_name

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




More information about the Pyrex mailing list