Advertisement
NLinker

offset_of macro

Jul 18th, 2018
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.08 KB | None | 0 0
  1. // λeonid Onokhov, [19.07.18 00:08]
  2. // А есть макрос offsetof для repr(C) структур?
  3.  
  4. // Антон, [19.07.18 00:24]
  5. // [In reply to λeonid Onokhov]
  6. // На, дарю:
  7. macro_rules! offset_of {
  8.     ($ty:ty, $field:ident) => {{
  9.         let struct_: $ty = unsafe { ::std::mem::uninitialized() };
  10.         let struct_offset: usize = &struct_ as * const _ as usize;
  11.         let field_offset: usize = &struct_.$field as * const _ as usize;
  12.         ::std::mem::forget(struct_);
  13.         field_offset - struct_offset
  14.     }}
  15. }
  16.  
  17. #[repr(C)]
  18. struct Foo {
  19.     a: u32,
  20.     b: char,
  21.     c: u32,
  22. }
  23.  
  24. fn main() {
  25.     println!("{}", offset_of!(Foo, a));
  26.     println!("{}", offset_of!(Foo, b));
  27.     println!("{}", offset_of!(Foo, c));
  28. }
  29.  
  30. // Vladimir, [19.07.18 00:50]
  31. // [In reply to Антон]
  32. // в сишном макросе юзается нулптр, если его заюзать, то будет без мемфоргета
  33.  
  34. macro_rules! offset_of {
  35.     ($ty:ty, $field:ident) => {{
  36.         unsafe{& (*(0 as * const $ty)).$field as *const _ as usize}
  37.     }}
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement