python中如何查看指定內存地址的內容


博客:博客園 | CSDN | blog

python中一般並不需要查看內存內容,但作為從C/C++過來的人,有的時候還是想看看內存,有時是為了驗證內容是否與預期一致,有時是為了探究下內存布局。

from sys import getsizeof 
from ctypes import string_at

'''
getsizeof(...)
    getsizeof(object, default) -> int
    Return the size of object in bytes.
    
string_at(ptr, size=-1)
    string_at(addr[, size]) -> string
    Return the string at addr.
'''

getsizeof用於獲取對象占用的內存大小,string_at用於獲取指定地址、指定字節長度的內容,因為返回的對象類型是bytes,可以調用hex()函數轉換成16進制查看。

int對象的內存內容如下,首先通過函數id獲取對象的內存地址。

i = 100
type(i)
# int
s = string_at(id(i), getsizeof(i))
type(s)
# bytes
s
# b'>\x00\x00\x00\x00\x00\x00\x00\xa0\x99\xfd\x1d\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00d\x00\x00\x00'
s.hex()
# '3e00000000000000a099fd1d00000000010000000000000064000000'

如果對int對象的內存布局不熟悉,可能看不出什么。

再舉一個numpy的例子。

>>> import numpy as np
>>> a = np.arange(12).reshape(3,4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

>>> a.data
<memory at 0x00000000062483A8>
>>> m = a.data
>>> type(m)
memoryview
>>> m.hex()
'000000000100000002000000030000000400000005000000060000000700000008000000090000000a0000000b000000'

>>> a.ctypes.data
68393696
>>> string_at(a.ctypes.data, a.nbytes).hex()
'000000000100000002000000030000000400000005000000060000000700000008000000090000000a0000000b000000'


上面展示的兩個例子,一個是通過memoryview對象查看,另一個是通過string_at查看。不是所有對象都支持memoryview

class memoryview(obj)

Create a memoryview that references obj. obj must support the buffer protocol. Built-in objects that support the buffer protocol include bytes and bytearray.

—— from https://docs.python.org/3/library/stdtypes.html#memoryview

string_at

ctypes.string_at(address, size=-1)

This function returns the C string starting at memory address address as a bytes object. If size is specified, it is used as size, otherwise the string is assumed to be zero-terminated.

—— from https://docs.python.org/3/library/ctypes.html?highlight=string_at#ctypes.string_at


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM