Skip to content

Instantly share code, notes, and snippets.

@m1el
Created May 4, 2020 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m1el/2dba0e9416976365b8c083865a34300b to your computer and use it in GitHub Desktop.
Save m1el/2dba0e9416976365b8c083865a34300b to your computer and use it in GitHub Desktop.
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