Can I Create a Reference to a Custom DST From Raw Parts on Stable?

I have a Custom DST like this:

#[repr(C)]
struct MyData {
  n: f32,
  data: [u32]
}

I also have a pointer to the data, and the length of the data, but is there a way to create a &mut MyData from the pointer and the length without requring nightly? It seems like std::ptr::from_raw_parts_mut is the way to do it, but it's only available on nightly.

You can go from *mut () to *mut [()] using std::ptr::slice_from_raw_parts, and then cast from *mut [()] to *mut MyData.

There's some discussion on whether this is actually guaranteed, but I think it clearly is.

3 Likes

Whoa, interesting, but what does that set the value of n to, then?

The pointer must point at a location where n is stored, followed by data.

1 Like

Gotcha. Wow, that's some hackery, but cool! Thanks!

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.