Struct class random access

castironpi castironpi at gmail.com
Wed Aug 27 07:06:52 CEST 2008


On Aug 26, 12:41 am, castironpi <castiro... at gmail.com> wrote:
> On Aug 25, 11:47 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>
> > On Mon, 25 Aug 2008 14:49:14 -0700, castironpi wrote:
> > > I'm interested in the speed benefit, so you don't have to reconstruct
> > > the entire 'record' just to read/write one 'field'.  How in ctypes?
>
> > Only the field accessed is converted.
>
> > Ciao,
> >         Marc 'BlackJack' Rintsch
>
> I know that.  I was asking how to write 'unpack_from( buf, off, 2 )',
> when buf is a non-ctypes buffer.

The code with ctypes is more elegant than I thought.

from ctypes import *
prototype= PYFUNCTYPE( c_int, py_object, POINTER(c_void_p),
POINTER(c_uint) )
PyObject_AsWriteBuffer= prototype( ( "PyObject_AsWriteBuffer",
pythonapi ) )
def refas( buf, offset, tp ):
    ''' return an instance of |tp| that refers to |offset| bytes into
buffer |buf| '''
    _b, _s= c_void_p(0), c_uint(0)
    PyObject_AsWriteBuffer( buf, byref(_b), byref(_s) ) #should return
0
    c= cast( _b.value+ offset, POINTER( tp ) )
    return c.contents

'tp' can be any class that is derived from ctypes.Structure.  'buf'
can be any object that supports the buffer protocol, including
'mmap'.  Remember when mapping pointers to store offsets, not memory
addresses.

I'd like to know how supported this is considered to be, across
platforms and versions.  Can I rely on this in the future?



More information about the Python-list mailing list