-
-
Save jeffs/8e528ffcf51149196513fef5390ba2ee to your computer and use it in GitHub Desktop.
nested-type-alignment-rs-crepr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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