Created
May 4, 2020 17:35
-
-
Save m1el/2dba0e9416976365b8c083865a34300b to your computer and use it in GitHub Desktop.
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
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