Reading struct with structs

Andrew Durdin adurdin at gmail.com
Tue Oct 12 19:30:03 EDT 2004


On Tue, 12 Oct 2004 17:27:29 -0400, Baillargeon, Sonny
<sonny.baillargeon at bmonb.com> wrote:
> 
> The custom structs are arbitrary.  The struct module only allows me to
> have strict C datatypes.  How can I read in a struct recursively given I
> have to feed the struct.unpack?

Here's one idea. Suppose we have the following structs:

struct foo {
    int x;
    int y;
};
struct bar {
    int a;
    struct foo;
}

If we've read in len(struct bar) bytes into a string s:

# This Thing is only for this example; presumably you'll be wanting
# to read the data into some other class instances.
class Thing(object): pass
bar = Thing()
bar.foo = Thing()

(bar.a, bar.foo.x, bar.foo.y) = struct.unpack("iii", s)



More information about the Python-list mailing list