更新ctypes指针 [英] Update ctypes pointer in place
问题描述
出于各种原因,我想就地更新ctypes指针的值.换句话说,我想要的是修改指针对象包装的内部缓冲区.这是一种可能的方法:
For various reasons I would like to update the value of a ctypes pointer in place. In other words, what I want is to modify the internal buffer the pointer object wraps. Here is one possible approach:
from ctypes import *
a = pointer(c_int(123))
b = pointer(c_int(456))
memmove(addressof(a), addressof(b), sizeof(c_void_p))
a._objects.clear()
a._objects.update(b._objects)
现在 a.contents
将返回 c_long(456)
.但是,使用_objects属性似乎太在意实现细节了(这甚至会正确地起作用吗?).有没有更惯用的方法来做到这一点?
Now a.contents
will return c_long(456)
. However, playing around with the _objects attribute seems like it's too concerned with the implementation details (will this even behave correctly?). Is there a more idiomatic way to do this?
推荐答案
由于eryksun尚未发布他的答案,所以我将在此处添加自己.这是应该这样做的方式:
Since eryksun hasn't posted up his answer I'll add it here my self. This is how it should be done:
from ctypes import *
a = pointer(c_int(123))
b = pointer(c_int(456))
tmp = pointer(a)[0]
tmp.contents = b.contents
现在 a.contents = c_int(456)
.关键是 tmp
与 a
共享一个缓冲区(这就是为什么您会找到 tmp._b_needsfree_ == 0
的原因).
Now a.contents = c_int(456)
. The key is that tmp
shares a buffer with a
(which is why you'll find tmp._b_needsfree_ == 0
).
这篇关于更新ctypes指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!