Python: how to increase instance instance of POINTER

Suppose p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char)) .

So we have p.contents.value == "f" .

How can I directly access and manipulate (e.g., increment) a pointer? For example. for example (p + 1).contents.value == "o" .

+7
source share
2 answers

You should use indexing:

 >>> p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char)) >>> p[0] 'f' >>> p[1] 'o' >>> p[3] '\x00' 

See the ctypes documentation to learn more about using pointers.

UPDATE . It seems that this is not what you need. Let's try a different approach: first hover over void, increment it and then return 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') 

It may not be elegant, but it works.

+7
source

Returning to this, I realized that @ Michaล‚ Bentkowski's answer is still not enough for me, because he did not change 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 
+4
source

All Articles