【问题标题】:How to updated the contents of the memory in the particular location?如何更新特定位置的内存内容?
【发布时间】:2021-04-28 07:54:30
【问题描述】:
我正在尝试使用 python 读取/写入和更新内存的内容。
我发现有很多方法可以继续,比如 mmap、memoryview、id() 和 ctypes。
我选择了 ctype 库,通过使用它,我可以获得地址,但我不知道如何更新内存特定位置的值。不幸的是,我现在还没有编写正确的代码。
这就是我没有分享的原因。
有人可以指导我吗?
提前致谢
【问题讨论】:
标签:
python-3.6
ctypes
mmap
memoryview
【解决方案1】:
您可以使用from_address 为一系列虚拟内存创建ctypes 缓冲区。
这是一个通常不可能的例子。它接受一个不可变的字符串,并使用 ctypes 缓冲区对其进行修改:
>>> from ctypes import *
>>> import sys
>>> s = 'xxxx'
>>> sys.getsizeof(s) # The size of the PyObject s represents
53
>>> id(s) # The address of the PyObject (implementation detail of CPython!)
2092123519664
>>> b=(c_char * sys.getsizeof(s)).from_address(id(s)) # A writeable ctypes buffer
>>> b.raw # Note xxxx in the last few bytes of the buffer.
b'\x02\x00\x00\x00\x00\x00\x00\x00\x90\xae7\x88\xfc\x7f\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x91\xb1\xe4,\xe4\x8d</\xe5\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00xxxx\x00'
>>> b[-2]=ord('y') # reassign the last 'x'
>>> s # changed the "immutable" string.
'xxxy'
所以使用(c_char * size).from_address(address) 模式在虚拟内存中创建一个可以读/写的窗口。