[Python-Dev] Extension of struct to handle non byte aligned values?

Michael Hudson mwh at python.net
Mon Aug 1 12:26:15 CEST 2005


"George V. Neville-Neil" <gnn at neville-neil.com> writes:

> Hi,
>
> I'm attempting to write a Packet class, and a few other classes for
> use in writing protocol conformance tests.  For the most part this is
> going well except that I'd like to be able to pack and unpack byte
> strings with values that are not 8 bit based quantities.

[...]

> Thoughts?

Well, the main thing that comes to mind is that I wouldn't regard the
struct interface as being something totally wonderful and perfect.

I am aware of a few attempts to make up a better interface, such as
ctypes and Bob's rather similar looking ptypes from macholib:

http://svn.red-bean.com/bob/py2app/trunk/src/macholib/ptypes.py

and various silly unreleased things I've done.  They all work on the
basic idea of a class schema that describes the binary structure, eg:

class Sound(Message):
    code = 0x06
    layout = [('mask', BYTE()),
              ('vol', CDI(1, SDI(BYTE(), 1/255.0), 1.0)),
              ('attenuation', CDI(2, SDI(BYTE(), 1/64.0), 1.0)),
              ('entitychan', SHORT()),
              ('soundnum', BYTE()),
              ('origin', COORD()*3)]

You may want to do something similar (presumably the struct module or
some other c stuff would be under the hood somewhere).

I don't really see a need to change CPython here, unless some general
binary parsing scheme becomes best-of-breed and a candidate for stdlib
inclusion.

Cheers,
mwh

PS: This is probably more comp.lang.python material.

-- 
  The use of COBOL cripples the mind; its teaching should, therefore,
  be regarded as a criminal offence.
           -- Edsger W. Dijkstra, SIGPLAN Notices, Volume 17, Number 5


More information about the Python-Dev mailing list