How to get pointer offset in bytes?

While raw pointers in Rust have a method offset, this only increases the size of the pointer. How can I access the pointer in bytes?

Something like this in C:

var_offset = (typeof(var))((char *)(var) + offset);
+3
source share
2 answers

From the answer, I contacted your previous question:

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);
}

When calculating p2, we can see that the pointer can be painlessly converted to an integer ( usizehere), on which arithmetic is performed, and then the result returns to the pointer.

isizeand usize- universal types of byte size pointers :)

+7
source

@Matthieu M. , , , heres :

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

macro_rules! check_type_pair {
    ($a:expr, $b:expr) => {
        if false {
            let _type_check = if false {$a} else {$b};
        }
    }
}

macro_rules! parent_of_mut {
    ($child:expr, $ty:ty, $field:ident) => {
        {
            check_type_pair!(&(*(0 as *const $ty)).$field, &$child);
            let offset = offset_of!($ty, $field);
            &mut *(((($child as *mut _) as usize) - offset) as *mut $ty)
        }
    }
}

macro_rules! parent_of {
    ($child:expr, $ty:ty, $field:ident) => {
        {
            check_type_pair!(&(*(0 as *const $ty)).$field, &$child);
            let offset = offset_of!($ty, $field);
            &*(((($child as *const _) as usize) - offset) as *const $ty)
        }
    }
}

, , :

fn some_method(&self) {
    // Where 'self' is ParentStruct.field,
    // access ParentStruct instance.
    let parent = unsafe { parent_of!(self, ParentStruct, field) };
}

check_type_pair , self ParentStruct.field . , .

+1

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


All Articles