ctypes pointer from offset into array?
sturlamolden
sturlamolden at yahoo.no
Sat Dec 5 11:47:08 EST 2009
On 5 Des, 10:13, Carl Banks <pavlovevide... at gmail.com> wrote:
> 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.
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)>
More information about the Python-list
mailing list