pythonpointersctypespyobject

accessing python object pointer data


I have a python set that contains a collection of non-hashable python objects with uniform type which I want to process.

To improve efficiency of my algorithms, I would like to interface using ctypes with an external index implementation that accepts only uint64 as data values.

I was hoping that I could to pass pointer references to the python object into this external library as uint64?

I tried ctypes.cast(ctypes.py_object(my_python_object), ctypes.c_uint64) but am getting ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type.

Also, what about the reverse, getting a reference to a python object as uint64 and turning it into a "real" python object?


Solution

  • Why wouldn't you simply use the id() function in CPython?

    >>> x
    <object object at 0x7fd2fc742090>
    >>> hex(id(x))
    '0x7fd2fc742090'
    

    The CPython documentation of id() says that

    id(object)

    Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

    CPython implementation detail: This is the address of the object in memory.


    You also need to mess with the reference counts and such, if you're to "convert" this uint64_t of yours back to a Python object. As far as I know, ctypes do not easily let one to increase/decrease the reference counts of Python