Assume p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char))
.
Thus, we have p.contents.value == "f"
.
How can I directly access and manipulate (e.g. increment) the pointer? E.g. like (p + 1).contents.value == "o"
.
You have to use indexing:
>>> p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char))
>>> p[0]
'f'
>>> p[1]
'o'
>>> p[3]
'\x00'
Have a look at ctypes documentation to find out more about using pointers.
UPDATE: It seems that it's not what you need. Let's, then, try another approach: first cast the pointer to void, increment it and then cast it back to LP_c_char:
In [93]: p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char))
In [94]: void_p = ctypes.cast(p, ctypes.c_voidp).value+1
In [95]: p = ctypes.cast(void_p, ctypes.POINTER(ctypes.c_char))
In [96]: p.contents
Out[96]: c_char('o')
Maybe it's not elegant but it works.
After getting back to this, I figured out that @Michał Bentkowski 's answer was still not enough for me because it didn't modified the original pointer.
This is my current solution:
a = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char))
aPtr = ctypes.cast(ctypes.pointer(a), ctypes.POINTER(c_void_p))
aPtr.contents.value += ctypes.sizeof(a._type_)
print a.contents
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With