在python中访问内存地址

Aca*_*mia 28 python memory memory-address

我的问题是:如何在python中读取内存地址的内容?示例:ptr = id(7)我想读取ptr指向的内存内容.谢谢.

Mar*_*nen 36

看看ctypes.string_at.这是一个例子.它转储Python 3整数的原始数据结构.希望你只是做这个练习.没有理由用纯Python做到这一点.

from ctypes import string_at
from sys import getsizeof
from binascii import hexlify
a = 0x7fff 
print(hexlify(string_at(id(a), getsizeof(a))))
Run Code Online (Sandbox Code Playgroud)

产量

b'02000000d8191e1e01000000ff7f'
Run Code Online (Sandbox Code Playgroud)

  • @MarkTolonen:重要的是不要注意这适用于*CPython*因为`id()`碰巧返回一个地址,对于这个实现,但语言本身并不保证这一点(即这可能不适用于Jython例如,IronPython或PyPy实现). (4认同)

Ray*_*ger 8

在Python中,除非您与C应用程序连接,否则通常不会使用指针来访问内存.如果这是您需要的,请查看访问者函数的ctypes模块.


S.L*_*ott 6

“我要读取ptr指向的内存内容”

用 C 编写代码。使用 Python 中的代码。 http://docs.python.org/extending/extending.html