unisgn
September 23, 2024, 7:22am
1
i want to have a packed struct like:
const S = packed struct {
a: u8,
b: u8,
padding: [510]u8
}
but the compiler complains that ‘packed structs cannot contain fields of type [510]u8’
how can i reconstruct this struct to make that @sizeOf (S) == 512 ?
although this
const S = packed struct {
a: u8,
b: u8,
padding: u4080
}
works for now.
is there any other good idea?
dimdin
September 23, 2024, 7:58am
2
Another way is to remove the padding and use an outer union:
const std = @import("std");
const S = packed struct {
a: u8,
b: u8,
};
const U = extern union {
s: S,
padding: [512]u8,
};
pub fn main() void {
const u = U{ .s = S{ .a = 0, .b = 1 } };
std.debug.print(
\\u.s={any}
\\sizeof(U)={d}
\\
, .{
u.s,
@sizeOf(U),
});
}
3 Likes
tstsrt
September 23, 2024, 8:35am
3
extern struct
follows the C ABI, so I use it for structs with well-defined padding locations:
const S = extern struct {
a: u8,
b: u8,
padding: [510]u8 = undefined
};
test "S properties" {
const assert = @import("std").debug.assert;
assert(@sizeOf(S) == 512);
const s = S{ .a = 1, .b = 2 };
assert(s.a == 1);
assert(s.b == 2);
}
3 Likes
unisgn
September 23, 2024, 12:47pm
4
both worked. so is extern a better packed?
kj4tmp
September 23, 2024, 10:40pm
6
If you are coming from C:
Packed struct in zig is different than attribute packed in C compilers. Packed struct in c compiler is closer to an extern struct in zig with align(...)
on all the fields.
https://ziglang.org/documentation/master/#Alignment
1 Like
kj4tmp
September 23, 2024, 10:42pm
7
We really need more info about this in the langref