Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

ctypes pointer from offset into array?

 

 

Python python RSS feed   Index | Next | Previous | View Threaded


pavlovevidence at gmail

Dec 5, 2009, 1:13 AM

Post #1 of 3 (209 views)
Permalink
ctypes pointer from offset into array?

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
--
http://mail.python.org/mailman/listinfo/python-list


sturlamolden at yahoo

Dec 5, 2009, 8:47 AM

Post #2 of 3 (184 views)
Permalink
Re: ctypes pointer from offset into array? [In reply 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.
> 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)>
--
http://mail.python.org/mailman/listinfo/python-list


sturlamolden at yahoo

Dec 5, 2009, 8:49 AM

Post #3 of 3 (185 views)
Permalink
Re: ctypes pointer from offset into array? [In reply 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.



--
http://mail.python.org/mailman/listinfo/python-list

Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.