Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

ctypes pointer from offset into array?

17 views
Skip to first unread message

Carl Banks

unread,
Dec 5, 2009, 4:13:37 AM12/5/09
to
Is there a way to get the pointer to an array offset in ctypes.
Example, say I define an array like so:

xfer = (c_char*bufsize)()

How would I get a pointer to then nth byte (equivalient of &xfer[n])?
I guess I would have expected xfer+n to work, but it doesn't.


Carl Banks

sturlamolden

unread,
Dec 5, 2009, 11:47:08 AM12/5/09
to

See:
http://bugs.python.org/issue6259


For now, we can still work with char* by casting them to an integer:

>>> from ctypes import *

>>> bufsize = 1024
>>> xfer = (c_char*bufsize)()

# cast to pointer

>>> ptr = cast(xfer, POINTER(c_char))


# obtain address

>>> addressof(xfer)
36279232
>>> addressof(ptr)
45151576
>>> addressof(ptr.contents)
36279232

# add offset to pointer

>>> cast(addressof(ptr.contents)+10,POINTER(c_char))
<ctypes.LP_c_char object at 0x02B0F580>

>>> cast(addressof(xfer)+10,POINTER(c_char))
<ctypes.LP_c_char object at 0x02B0FDA0>


# byref also takes an offset

>>> byref(xfer,0)
<cparam 'P' (022993C0)>

>>> byref(xfer,10)
<cparam 'P' (022993CA)>

sturlamolden

unread,
Dec 5, 2009, 11:49:19 AM12/5/09
to
On 5 Des, 10:13, Carl Banks <pavlovevide...@gmail.com> wrote:
> Is there a way to get the pointer to an array offset in ctypes.

Could also mention that Cython has pointer arithmetics. Cython can be
easier to use than ctypes, but is not a standard module.

0 new messages