How to get the address of &T where T: ?Sized

How to get the address of T if it may be a DST (Dynamic Sized Type)?

TLDR, How to write the following function?

pub fn get_addr_len_pair<T: ?Sized>(item: &T) -> (usize, usize) {
   (todo!() /* address */,  core::mem::size_of_val(item))
}

item as *const T as usize does not work that compile errors with
casting *const T as usize is invalid: needs casting through a thin pointer first

core::ptr::addr_of(item) not work either, which gives a wrong address.

If a type has zero size, then there might not be an address.

So, if T were a dynamic trait object, you could define a trait method to return the address of the concrete type.

1 Like

You can cast the *const T to a *const () and then cast that to a usize

pub fn get_addr_len_pair<T: ?Sized>(item: &T) -> (usize, usize) {
   (item as *const T as *const () as usize,  core::mem::size_of_val(item))
}
4 Likes

That should be core::ptr::addr_of!(*item) to get the right place inside, and with Rust 1.82 you'll be able to write &raw const *item. Then you can cast as *const () as usize, and once strict provenance stabilizes, you'll be able to write (&raw const *item).addr() or .expose_provenance().

ZSTs do still have an address, although if it's not a member of a larger struct, then it might just be an otherwise-dangling pointer since there's nothing to dereference. Such pointers will always be aligned though.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.