Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
macro_rules! field_offset {
($ty:path, $field:ident$(.$cfield:ident)*) => {
unsafe {
union Transmuter<T: 'static> {
p: *const T,
r: &'static T,
i: usize,
}
let base = Transmuter::<$ty> {
p: core::ptr::NonNull::dangling().as_ptr(),
};
let field = Transmuter {
r: &base.r.$field$(.$cfield)*,
};
field.i - base.i
}
}
}
#[repr(C)]
struct Foo {
x: u8,
y: u16,
}
fn main () {
println!("offsets: {}, {}", field_offset!(Foo, x), field_offset!(Foo, y));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment