I wanted to get a reference to structure from member references. So, I wrote the following code.
#[repr(C)]
struct Data {
x: i32,
y: u32,
}
fn compose<'a>(x: &'a i32, y: &'a u32) -> Option<&'a Data> {
use memoffset::offset_of;
let x_address = x as *const i32 as usize;
let y_address = y as *const u32 as usize;
if x_address + offset_of!(Data, y) != y_address {
return None;
}
return Some(unsafe { &*(x_address as *const Data) });
}
It seems to work correctly but I don't know if it is safe or not. Is this undefined behavior or is there a good crate for solving this problem?