Example calculating offset of field in Rust


#1

I have the following code:

#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct SdfVertex {
    pub pos: Vec3F32,
    pub color: Vec3F32,
    pub tex: Vec2F32,
    pub flat:  f32,
}

I need to get the offset of color, tex relative to the start of a SdfVertex.

I know of https://docs.rs/field-offset/0.1.1/field_offset/macro.offset_of.html but it is not clear how to use it.

Can someone give me a 1 line example of how to get the offsets of color / tex?

Thanks!


#2

If you look at the source for that crate, you can see it being used in tests. Looks like this is what you want:

let color_offset = offset_of!(SdfVertex => color);
let tex_offset = offset_of!(SdfVertex => tex);

You can then use the apply/apply_mut methods to do the pointer offsetting within a given object.


#3

The page for that macro really ought to have a link to the output type.


#4

@skyschermer @ExpHP : Resolved. Thanks!