writeable buffer and struct.pack_into and struct.unpck_from

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Sep 21 01:42:58 CEST 2008

En Sat, 20 Sep 2008 15:45:48 -0300, Tzury Bar Yochay  
<Afro.Systems at gmail.com> escribió:

> I can't find in the documentation the way to use these two functions.
> can someone share a simple code that utilize these two functions?

struct.pack_into is intended to "fill" a buffer you got from somewhere,  
probably other language or process. ctypes.create_string_buffer may be  
used to create a writable buffer in python code.

py> from ctypes import create_string_buffer
py> b = create_string_buffer(10)
py> b.raw
py> from struct import *
py> pack_into("hhh", b, 0, 1, 2, -1)
py> b.raw

unpack_from does the opposite.
Before Python 2.5, you had to use pack to create a string object, and then  
copy its contents into the destination buffer; using pack_into avoids the  
memory copy.

Gabriel Genellina

More information about the Python-list mailing list