writeable buffer and struct.pack_into and struct.unpck_from

T

Tzury Bar Yochay

Hi,

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?
 
G

Gabriel Genellina

En Sat, 20 Sep 2008 15:45:48 -0300, Tzury Bar Yochay
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
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
py> from struct import *
py> pack_into("hhh", b, 0, 1, 2, -1)
py> b.raw
'\x01\x00\x02\x00\xff\xff\x00\x00\x00\x00'

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.
 
A

Aaron \Castironpi\ Brady

En Sat, 20 Sep 2008 15:45:48 -0300, Tzury Bar Yochay  



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
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
py> from struct import *
py> pack_into("hhh", b, 0, 1, 2, -1)
py> b.raw
'\x01\x00\x02\x00\xff\xff\x00\x00\x00\x00'

unpack_from does the opposite.
Before Python 2.5,

That was when Python broke string immutability with the ctypes module.
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.

'mmap' seems to have always offered random-access writes. A search
through the implementation for "tp_as_buffer" returns a lot of zeros
however.
 
T

Tzury Bar Yochay

Thanks Gabriel,
I was missing the information how to create a writable buffer.
 
J

John Machin

Thanks Gabriel,
I was missing the information how to create a writable buffer.

array.array objects also have the writable buffer nature:
array('c', '\x01\x00\x02\x00\xff\xff\x00\x80\x00\x00')

HTH,
John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top