4 ms·
A solution used in the Linux kernel[0] is to use a struct with the packed attribute, which implies the fields aren't necessarily aligned. Simplifying, I think t
by mlochbaum 3y ago
A solution used in the Linux kernel[0] is to use a struct with the packed attribute, which implies the fields aren't necessarily aligned. Simplifying, I think this macro should work the same in gcc and similar: apply to any pointer to get something that behaves as *p but will read or write as unaligned.
#define unaligned(P) (((struct { typeof(*(P)) x; } __attribute__((packed))*)(P))->x)
[0] https://github.com/torvalds/linux/blob/7b9e664beb237d90bc600f117668227af5ce53ae/include/asm-generic/unaligned.h#L12-L15 https://github.com/torvalds/linux/blob/7b9e664beb237d90bc600...
- JonChesterfield 3y agoUses of pointers to members of packed structs are prone to being miscompiled by GCC so I suspect that only works in combination with the various other not-actually-C flags the kernel has to pass around.