Вопрос

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)

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?

Это было полезно?

Решение

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

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).

Другие советы

A pointer is a variable that holds a memory address, so the call memmove(addressof(a), addressof(b),...) actually copies the address held by b into a so a now points at the same memory location that b points to. If that is what you desire, you're done.

If what you want is to set the value of the integer pointed to by a to the same value as that of the integer pointed to by b, then what you need is to copy the contents of the memory at the address pointed to by b into the memory pointed to by a. Like so...

memmove(cast(a, c_void_p).value, cast(b, c_void_p).value, sizeof(c_int))

now the pointer a points to a memory address that holds a value similar to the value stored at the memory pointed to by b.

the _objects attribute is not necessary in both cases (IMHO)

Sorry for the boring post. But that I'm afraid is the (only?) way to do pointers :)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top