How to memory dump an object?

jfong at ms4.hinet.net jfong at ms4.hinet.net
Sat May 21 00:47:16 EDT 2016


Sorry, forget to mention that I am working on version 3.4

Following the steps given in Chris's reply, I get the result from bytes string:

>>> b1 = b'\x80abc'
>>> ctypes.cast(id(b1), ctypes.c_voidp)
c_void_p(35495992)
>>> sys.getsizeof(b1)
21
>>> b1ptr = ctypes.cast(id(b1), ctypes.POINTER(ctypes.c_uint8))
>>> bytes([b1ptr[i] for i in range(21)])
b'\x01\x00\x00\x00X\xa1e^\x04\x00\x00\x00\x04\xff\x04&\x80abc\x00'
>>>

It obviously has the same "content" as the s1 string has and the object's structure are much different as expected (77 vs 21 bytes:-)

If I do this as Ned suggested:

>>> b2 = b1

I get:

>>> bytes([b1ptr[i] for i in range(21)])
b'\x02\x00\x00\x00X\xa1e^\x04\x00\x00\x00\x04\xff\x04&\x80abc\x00'
>>>

So, at least, we know where the reference count was stored:-)

It's amazing the "tool" is so simple. Actually I feel a little embarrassed that I do know every statements in it but just no idea of combining them together. Thanks a lot, Chris.

--Jach



More information about the Python-list mailing list