Low-Level Memory
30.1 Alignment
var buf: [64]u8 align(16) = undefined; // aligned array
const p: *align(16) [64]u8 = &buf;
fn needsAligned(ptr: *align(64) const u8) void { _ = ptr; }
std.debug.print("{d}\n", .{@alignOf(u64)});
const raw: [*]u8 = &buf;
const as_u32: [*]u32 = @ptrCast(@alignCast(raw)); // checked alignment cast
_ = .{ p, as_u32 };30.2 Packed Structs for Bit Fields and Registers
const ControlReg = packed struct(u32) {
enable: bool,
mode: u2,
prescaler: u5,
_reserved: u24 = 0,
};
const reg: *volatile ControlReg = @ptrFromInt(0x4000_0000); // MMIO register
reg.* = .{ .enable = true, .mode = 2, .prescaler = 7 };30.3 Extern Structs and ABI
extern struct / extern union follow the C ABI. Use them for FFI, file formats, and network protocols (with explicit endianness conversions via std.mem.readInt, @byteSwap, std.mem.nativeToBig).
30.4 Volatile and Memory-Mapped I/O
*volatile T means every read and write is performed (not optimized away). It's for hardware registers. volatile is not a synchronization primitive. Use atomics for threads.
30.5 Opaque Types
const Handle = opaque {}; // unknown size/layout (like a C incomplete struct)
extern fn create_handle() *Handle;
extern fn destroy_handle(h: *Handle) void;30.6 Linker Sections and Exports
export var counter: u32 linksection(".data.custom") = 0;
comptime { @export(&myFn, .{ .name = "my_fn", .linkage = .strong }); }