Kev*_*n91 5 python ctypes pointers
我知道如何通过 Python 中的 id 获取变量的值,例如:
a = "hello world!"
ctypes.cast(id(a), ctypes.py_object).value
Run Code Online (Sandbox Code Playgroud)
我想知道是否可以通过 id 覆盖变量值?
最简单的方法,这个:
ctypes.cast(id(a), ctypes.py_object).value = "new value"
Run Code Online (Sandbox Code Playgroud)
不起作用。
该对象ctypes.cast(id(a), ctypes.py_object)仅提供内存中对象的视图。因此,当更新value属性时,您不会更新对象本身,您所做的只是创建一个新对象并value指向它。
import ctypes
a = "Hello World!"
py_obj = ctypes.cast(id(a), ctypes.py_object)
id(py_obj.value) # 1868526529136
py_obj.value = 'Bye Bye World!'
# Here we can see that `value` now points to a new object
id(py_obj.value) # 1868528280112
Run Code Online (Sandbox Code Playgroud)
可以使用ctypes直接更新内存,从而改变任何对象。对于被称为不可变的字符串,情况也是如此。
以下作为练习很有趣,但不应在其他情况下使用。除其他外,它可能会破坏对象引用计数,从而导致内存管理错误。
import ctypes
import sys
def mutate(obj, new_obj):
if sys.getsizeof(obj) != sys.getsizeof(new_obj):
raise ValueError('objects must have same size')
mem = (ctypes.c_byte * sys.getsizeof(obj)).from_address(id(obj))
new_mem = (ctypes.c_byte * sys.getsizeof(new_obj)).from_address(id(new_obj))
for i in range(len(mem)):
mem[i] = new_mem[i]
Run Code Online (Sandbox Code Playgroud)
以下是示例。在这些中,您会找到为什么不能使用上述代码的原因,除非您真的知道自己在做什么或作为练习。
s = 'Hello World!'
mutate(s, 'Bye World!!!')
print(s) # prints: 'Bye World!!!'
# The following happen because of Python interning
mutate('a', 'b')
print('a') # prints: 'b'
mutate(1, 2)
print(1) # prints: 2
Run Code Online (Sandbox Code Playgroud)
特别是,上面的例子让 Python 以未知的错误代码退出或崩溃,这取决于版本和环境。
a是一个字符串,并且字符串在Python中是不可变的。
文档中的示例:
>>> s = "Hello, World"
>>> c_s = c_wchar_p(s)
>>> print(c_s)
c_wchar_p(139966785747344)
>>> print(c_s.value)
Hello World
>>> c_s.value = "Hi, there"
>>> print(c_s) # the memory location has changed
c_wchar_p(139966783348904)
>>> print(c_s.value)
Hi, there
>>> print(s) # first object is unchanged
Hello, World
>>>
Run Code Online (Sandbox Code Playgroud)