// λeonid Onokhov, [19.07.18 00:08]
// А есть макрос offsetof для repr(C) структур?
// Антон, [19.07.18 00:24]
// [In reply to λeonid Onokhov]
// На, дарю:
macro_rules! offset_of {
($ty:ty, $field:ident) => {{
let struct_: $ty = unsafe { ::std::mem::uninitialized() };
let struct_offset: usize = &struct_ as * const _ as usize;
let field_offset: usize = &struct_.$field as * const _ as usize;
::std::mem::forget(struct_);
field_offset - struct_offset
}}
}
#[repr(C)]
struct Foo {
a: u32,
b: char,
c: u32,
}
fn main() {
println!("{}", offset_of!(Foo, a));
println!("{}", offset_of!(Foo, b));
println!("{}", offset_of!(Foo, c));
}
// Vladimir, [19.07.18 00:50]
// [In reply to Антон]
// в сишном макросе юзается нулптр, если его заюзать, то будет без мемфоргета
macro_rules! offset_of {
($ty:ty, $field:ident) => {{
unsafe{& (*(0 as * const $ty)).$field as *const _ as usize}
}}
}
Comments