Skip to content

Instantly share code, notes, and snippets.

@rlane
Created January 24, 2014 07:50
Show Gist options
  • Save rlane/8593632 to your computer and use it in GitHub Desktop.
Save rlane/8593632 to your computer and use it in GitHub Desktop.
macro_rules! offset_of(
($typename:ident, $fieldname:ident) => (
unsafe {
let ptr = std::ptr::null::<$typename>();
std::ptr::to_unsafe_ptr(&(*ptr).$fieldname).to_uint() -
ptr.to_uint()
}
);
)
#[test]
fn test_offset_of() {
struct Foo {
a: i32,
b: u8,
c: u16,
};
assert_eq!(offset_of!(Foo, a), 0);
assert_eq!(offset_of!(Foo, b), 4);
assert_eq!(offset_of!(Foo, c), 6);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment