Home > OS >  Rust: Convert a mutable u8 pointer to a mutable reference
Rust: Convert a mutable u8 pointer to a mutable reference

Time:11-30

How can I convert a mutable u8 pointer to a mutable reference of another type?

let ptr: *mut u8;

let reference: &mut SomeType = ?; // What should i do here?

I have found a sort-of viable solution, but I wonder if there is a better way:

let reference = unsafe { &mut *(ptr as *mut SomeType) };

CodePudding user response:

You have already found an acceptable method. A slightly preferable one is to use pointer::cast instead of as, because that explicitly specifies that you are trying to change the type of the referent and not any of the many other things as can do.

let ptr = ptr.cast::<SomeType>();
let reference = unsafe { &mut *ptr };

Do not use std::mem::transmute for this. Transmuting should always be the last resort in any circumstance (the nomicon and function documentation say so!), because it reinterprets the bytes regardless of what they are — in this case it'll convert any pointer-sized value, such as a reference to the pointer. By sticking with cast and &*, we catch more possible type errors. (Clippy even has a default lint against using transmute here.)

CodePudding user response:

You could use std::mem::transmute instead:

use std::mem::transmute;
#[repr(transparent)]
struct SomeStruct(u8);

fn main() {
    let a = &mut 10u8;
    let ptr = a as *mut u8;
    let reference: &mut SomeStruct = unsafe { transmute(ptr) };
}
  • Related