Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3.3 dict: how to convert struct PyDictKeysObject to python class?

I am trying to modify Brandon Rhodes code Routines that examine the internals of a CPython dictionary so that it works for CPython 3.3.

I believe I have translated this struct successfully.

typedef PyDictKeyEntry *(*dict_lookup_func)
    (PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr);

struct _dictkeysobject {
    Py_ssize_t dk_refcnt;
    Py_ssize_t dk_size;
    dict_lookup_func dk_lookup;
    Py_ssize_t dk_usable;
    PyDictKeyEntry dk_entries[1];
};

I think the following looks good now:

from ctypes import Structure, c_ulong, POINTER, cast, py_object, CFUNCTYPE

LOOKUPFUNC = CFUNCTYPE(POINTER(PyDictKeyEntry), POINTER(PyDictObject), 
                       py_object, c_ulong, POINTER(POINTER(py_object)))

class PyDictKeysObject(Structure):
"""A key object"""
_fields_ = [
    ('dk_refcnt', c_ssize_t),
    ('dk_size', c_ssize_t),
    ('dk_lookup', LOOKUPFUNC),
    ('dk_usable', c_ssize_t),
    ('dk_entries', PyDictKeyEntry * 1),
]

PyDictKeysObject._dk_entries = PyDictKeysObject.dk_entries
PyDictKeysObject.dk_entries = property(lambda s: 
    cast(s._dk_entries, POINTER(PyDictKeyEntry * s.dk_size))[0])

This line of code now works, where d == {0: 0, 1: 1, 2: 2, 3: 3}:

obj = cast(id(d), POINTER(PyDictObject)).contents  # works!!`

Here is my translation from the C struct PyDictObject:

class PyDictObject(Structure):  # an incomplete type
    """A dictionary object."""

def __len__(self):
    """Return the number of dictionary entry slots."""
    pass

def slot_of(self, key):
    """Find and return the slot at which `key` is stored."""
    pass

def slot_map(self):
    """Return a mapping of keys to their integer slot numbers."""
    pass

PyDictObject._fields_ = [
    ('ob_refcnt', c_ssize_t),
    ('ob_type', c_void_p),
    ('ma_used', c_ssize_t),
    ('ma_keys', POINTER(PyDictKeysObject)),
    ('ma_values', POINTER(py_object)),  # points to array of ptrs
]
like image 874
LeslieK Avatar asked Oct 20 '22 09:10

LeslieK


1 Answers

My problem was to access the C struct underlying a python dictionary implemented in Cpython 3.3. I started with the C structs provided in cpython/Objects/dictobject.c and Include/dictobject.h . Three C structs are involved in defining the dictionary: PyDictObject, PyDictKeysObject, and PyDictKeyEntry. The correct translation of each C struct into python is as follows. The comments indicate where I needed to make fixes. Thank you to @eryksun for guiding me along the way!!

class PyDictKeyEntry(Structure):
"""An entry in a dictionary."""
    _fields_ = [
        ('me_hash', c_ulong),
        ('me_key', py_object),
        ('me_value', py_object),
    ]

class PyDictObject(Structure):
    """A dictionary object."""
    pass

LOOKUPFUNC = CFUNCTYPE(POINTER(PyDictKeyEntry), POINTER(PyDictObject), py_object, c_ulong, POINTER(POINTER(py_object)))

class PyDictKeysObject(Structure):
"""An object of key entries."""
    _fields_ = [
        ('dk_refcnt', c_ssize_t),
        ('dk_size', c_ssize_t),
        ('dk_lookup', LOOKUPFUNC),  # a function prototype per docs 
        ('dk_usable', c_ssize_t),
        ('dk_entries', PyDictKeyEntry * 1),  # an array of size 1; size grows as keys are inserted into dictionary; this variable-sized field was the trickiest part to translate into python
    ]   

PyDictObject._fields_ = [
    ('ob_refcnt', c_ssize_t),  # Py_ssize_t translates to c_ssize_t per ctypes docs
    ('ob_type', c_void_p),     # could not find this in the docs
    ('ma_used', c_ssize_t),
    ('ma_keys', POINTER(PyDictKeysObject)),
    ('ma_values', POINTER(py_object)),  # Py_Object* translates to py_object per ctypes docs
]

PyDictKeysObject._dk_entries = PyDictKeysObject.dk_entries
PyDictKeysObject.dk_entries = property(lambda s: cast(s._dk_entries, POINTER(PyDictKeyEntry * s.dk_size))[0])  # this line is called every time the attribute dk_entries is accessed by a PyDictKeyEntry instance; it returns an array of size dk_size starting at address _dk_entries. (POINTER creates a pointer to the entire array; the pointer is dereferenced (using [0]) to return the entire array); the code then accesses the ith element of the array)

The following function provides access to the PyDictObject underlying the python dictionary:

def dictobject(d):
    """Return the PyDictObject lying behind the Python dict `d`."""
    if not isinstance(d, dict):
        raise TypeError('cannot create a dictobject from %r' % (d,))
    return cast(id(d), POINTER(PyDictObject)).contents

If d is a python dictionary with key-value pairs, then obj is the PyDictObject instance that contains the key-value pairs:

obj = cast(id(d), POINTER(PyDictObject)).contents

An instance of the PyDictKeysObject is:

key_obj = obj.ma_keys.contents

A pointer to the key stored in slot 0 of the dictionary is:

key_obj.dk_entries[0].me_key

The program that uses these classes, together with routines that probe the hash collisions of each key inserted into a dictionary, is located here. My code is a modification of code written by Brandon Rhodes for python 2.x. His code is here.

like image 110
LeslieK Avatar answered Oct 23 '22 02:10

LeslieK