How to get a pointer to the containing structure from a pointer to a member?

I have a type:

struct Foo {
    memberA: Bar,
    memberB: Baz,
}

and the pointer that I know is a pointer to memberBin Foo:

p: *const Baz

What is the correct way to get a new pointer p: *const Foothat points to the original structure Foo?

My current implementation is as follows: I'm sure it is calling undefined behavior due to dereferencing (p as *const Foo), where pit is not a pointer to Foo:

let p2 = p as usize -
    ((&(*(p as *const Foo)).memberB as *const _ as usize) - (p as usize));

This is part of FFI - I cannot easily rebuild the code to avoid having to perform this operation.

This is very similar to Get a pointer to an object from a pointer to some element , but for Rust, which, as far as I know, does not have a macro offsetof.

+3
1

lvalue, lvalue , , . .

, , ( 0). , C/ , offsetof, , .

fn main() {
    let p: *const Baz = 0x1248 as *const _;
    let p2: *const Foo = unsafe { ((p as usize) - (&(*(0 as *const Foo)).memberB as *const _ as usize)) as *const _ };
    println!("{:p}", p2);
}

offset_of!:

macro_rules! offset_of {
    ($ty:ty, $field:ident) => {
        unsafe { &(*(0 as *const $ty)).$field as *const _ as usize }
    }
}

fn main() {
    let p: *const Baz = 0x1248 as *const _;
    let p2: *const Foo = ((p as usize) - offset_of!(Foo, memberB)) as *const _;
    println!("{:p}", p2);
}
+5

Source: https://habr.com/ru/post/1659380/


All Articles