Skip to content

Instantly share code, notes, and snippets.

@Renkai
Created February 7, 2020 07:50
Show Gist options
  • Save Renkai/be64c6ee7d68f7a34da131d7116af389 to your computer and use it in GitHub Desktop.
Save Renkai/be64c6ee7d68f7a34da131d7116af389 to your computer and use it in GitHub Desktop.
fetch reference by offset
struct Foo {
x: u32,
y: f64,
}
fn main() {
let foo = Foo {
x: 1,
y: 1.024,
};
let offset_x = &(foo.x) as *const u32 as usize - (&foo as *const Foo as usize);
let offset_y = &(foo.y) as *const f64 as usize - (&foo as *const Foo as usize);
unsafe {
println!("jj");
let x_by_offset = &*((&foo as *const Foo as usize + offset_x) as *const u32);
let y_by_offset = &*((&foo as *const Foo as usize + offset_y) as *const f64);
println!("dandan");
println!("x: {},y: {}", x_by_offset, y_by_offset);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment