pythoncpython

Is it possible to access an object via memory address?


In CPython, the builtin-function id(x) returns the memory address of x.
Is it possible to reverse this ?

Something like object_by_memoryadress(id(x)) == x.

Update: The reason I need this is, because I'm using a program with embedded Python. And in this program I can create so called "Nodes" that can communicate with each other, but only with integers, strings, and stuff, but I'd need to "transfer" a list between them (which is not possible the usual way).


Solution

  • I have created a shared library that contains the following code:

    #include "Python.h"
    extern "C" __declspec(dllexport) PyObject* PyObjectFromAdress(long addr) {
        return (PyObject*) addr;
    }
    

    compiled it and wrapped it using ctypes:

    import ctypes
    dll = ctyes.cdll.thedll
    object_from_id = dll.PyObjectFromAdress
    object_from_id.restype = ctypes.py_object
    

    Now you can exchange python objects through their memory adress within one python process.

    l1 = []
    l2 = object_from_id( id(l1) )
    print l1 == l2
    l1.append(9)
    print l2
    

    But be aware of already garbage collected objects ! The following code will crash the Python interpreter.

    l2 = object_from_id( id([]) )
    l2.append(8)