Python ctypes memory reading skills

Because I like to look at the variable structure in the memory, I came into contact with this library early, and found another usage today, so I sorted it out!

Read the contents of the variable in the memory

ctypes.string_at(ptr, size=-1)
Get the byte of the specified address and specified length in the memory, only one byte is obtained by default

ctypes.string_at(id(a),sys.getsizeof(a))
Because the first 16 bytes of Python variables are displayed (unknown type), the data content starts from the back. So the first 16 bytes can be skipped.

Determine the variable content of the memory address

ctypes.cast(obj, typ)
ctypes.cast(id(a),ctypes.py_object).value
Note that the address here needs to be a real variable address, if it is not a variable address, it will run violently, jump out, etc.

ctypes.cast(int.from_bytes(bytes.fromhex(‘10 6a c4 37 ee 01 00 00’),byteorder=‘little’), ctypes.py_object).value

The mechanism is very simple, that is, familiar with the structure of the data type, get the type according to the second set of bytes, analyze the data's memory validity according to the structure of the type, and decode the content

Guess you like

Origin blog.csdn.net/jhsxy2005/article/details/114371993