Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to increment a ctypes POINTER instance

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

like image 821
Albert Avatar asked Jul 14 '11 11:07

Albert


2 Answers

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.

like image 121
Michał Bentkowski Avatar answered Oct 20 '22 15:10

Michał Bentkowski


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
like image 44
Albert Avatar answered Oct 20 '22 16:10

Albert