#Packed struct size

1 messages · Page 1 of 1 (latest)

wraith cape
#

Im new to zig an I ran into this issue:

With this C code the size of the packed struct is 9 bytes

typedef struct {
    u8 foo;
    u64 baa;
} __attribute__((packed)) MyPackedStruct;
_Static_assert(sizeof(MyPackedStruct) == 9, "");

But when I tried to replicate this behaviour with zig the struct
size is 16 bytes

const MyPackedStruct = packed struct {
    foo: u8,
    baa: u64,
};
comptime {
    @compileLog(@sizeOf(MyPackedStruct));
    @import("std").debug.assert(@sizeOf(MyPackedStruct) == 9);
}

I tested this on master an on 0.13.0, what am I doing wrong?

small jolt
#

zigs packed structs are bit packed and defined to have the same ABI as their backing int, attribute packed in C is byte packed

#

you want extern struct with align(1) on each field

wraith cape
#
const MyPackedStruct = extern struct {
    foo: u8 align(1),
    baa: u64 align(1),
};
comptime {
    @compileLog(@sizeOf(MyPackedStruct));
    @import("std").debug.assert(@sizeOf(MyPackedStruct) == 9);
}
#

this works