I have a type:
struct Foo {
memberA: Bar,
memberB: Baz,
}
and a pointer which I know is a pointer to memberB
in Foo
:
p: *const Baz
What is the correct way to get a new pointer p: *const Foo
which points to the original struct Foo
?
My current implementation is the following, which I'm pretty sure invokes undefined behavior due to the dereference of (p as *const Foo)
where p
is not a pointer to a Foo
:
let p2 = p as usize -
((&(*(p as *const Foo)).memberB as *const _ as usize) - (p as usize));
This is part of FFI - I can't easily restructure the code to avoid needing to perform this operation.
This is very similar to Get pointer to object from pointer to some member but for Rust, which as far as I know has no offsetof
macro.