8

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

1
  • This is not always such a hot idea in C; to see someone want to apply it to Python scares me a bit. Commented Jul 14, 2011 at 12:02

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't really answer my question. I really want to modify/increment p. If p would be a c_void_p, I could do p.value += 1.
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.