Skip to content

Instantly share code, notes, and snippets.

@jeffs

jeffs/main.rs Secret

Last active July 26, 2021 17:13
Show Gist options
  • Save jeffs/8e528ffcf51149196513fef5390ba2ee to your computer and use it in GitHub Desktop.
Save jeffs/8e528ffcf51149196513fef5390ba2ee to your computer and use it in GitHub Desktop.
nested-type-alignment-rs-crepr
#[repr(C)]
struct CRepr {
a: u16, // 2 bytes
b: u32, // 4 bytes
c: u16, // 2 bytes
d: u32, // 4 bytes
}
fn address<T>(r: &T) -> isize {
r as *const _ as isize
}
fn main() {
let object = CRepr { a: 0, b: 0, c: 0, d: 0 };
let offset = |p| p - address(&object);
println!("Rust struct with C-like layout:\n");
println!(" offset of a: {:2} bytes", offset(address(&object.a)));
println!(" offset of b: {:2} bytes", offset(address(&object.b)));
println!(" offset of c: {:2} bytes", offset(address(&object.c)));
println!(" offset of d: {:2} bytes", offset(address(&object.d)));
println!(" total size: {:2} bytes", std::mem::size_of::<CRepr>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment