My question is: How can I read the content of a memory address in python? example: ptr = id(7) I want to read the content of memory pointed by ptr. Thanks.
Have a look at ctypes.string_at. Here's an example. It dumps the raw data structure of a Python 3 integer. Hopefully you're only doing this as an exercise. No reason to do this with pure Python.
from ctypes import string_at
from sys import getsizeof
from binascii import hexlify
a = 0x7fff
print(hexlify(string_at(id(a), getsizeof(a))))
Output
b'02000000d8191e1e01000000ff7f'
In Python, you don't generally use pointers to access memory unless you're interfacing with a C application. If that is what you need, have a look at the ctypes module for the accessor functions.
"I want to read the content of memory pointed by ptr"
Write code in C. Use the code from Python. http://docs.python.org/extending/extending.html
Are you trying to "reverse" id to get the Python object thing from the result of id(thing)? I don't even know if that can be done, and it definitely shouldn't be done; it would defeat garbage collection and lead to a lack of memory safety. If your program does that it means you effectively have references to things (the id numbers) that the garbage collector doesn't know are references, so it could release objects you're still using (depending on what happens in the rest of the program).
If you're trying to read raw memory from a pointer that you've got returned from a C extension or something, then the other answers may help you.
来源:https://stackoverflow.com/questions/8250625/access-memory-address-in-python