Direct access to the internal fields of a CPython object

24 Views Asked by At

To improve my understanding of Cython, I am trying to find a way to directly access the fields of the objects defined by CPython.

For example, I wrote the following code to access the ob_item field of a PyTupleObject:

from cpython.ref cimport PyObject

cdef extern from "Python.h":
    ctypedef struct PyTupleObject:
        PyObject *ob_item[1]

cdef void f(PyTupleObject* pto):
    cdef unsigned i
    cdef object item

    for i in range(5):
        item = <object>pto.ob_item[i]
        print(item)

t = (1,2,3,4,5)
f(<PyTupleObject*>t)

Two questions here:

  1. By doing so, did I mess with the object's reference counting, or is it ok?
  2. How to call Py_SIZE on the PyTupleObject to retrieve the length of the tuple?
0

There are 0 best solutions below