Here's a minimal example of what I'm trying to do:
#[repr(C)]
pub struct Example {
foo: u32,
bar: usize,
}
impl Example {
/// The byte offset of `Example::bar`
const BAR_OFFSET: usize = {
// what goes here?
};
}
I could use size_of::<u32>() and align_of::<usize>() to manually calculate the offset but that feels brittle. If it weren't a const I could construct a dummy value and do pointer arithmetic. Are there better options?
FWIW, although ::memoffset is currently the best effort to get the offset for #[repr(C)]structs that come from external crates, its implementation is technically UB, so if the definition comes from your own crate, you should take advantage of that to get offsets without unsafe and thus without UB:
#![forbid(unsafe_code)]
// ...
with_offsets! {
#[repr(C)]
pub
struct Example {
#[offset(FOO_OFFSET)]
foo: u32,
#[offset(BAR_OFFSET)]
bar: usize,
}
}
fn main ()
{
dbg!(Example::BAR_OFFSET); // outputs 8 on the Playground
}