Search code examples
rustunsafelow-levelmemmoveraw-pointer

Copy a struct to a specific memory location in Rust


If I have a struct, for example:

#[derive(Clone, Copy)]
#[repr(C, packed)]
pub struct SomeData {
    a: u16,
    b: u64,
    c: u32,
    d: u16,
}

How do I copy it to a specific location in memory, e.g. to a point 0x1000 in memory efficiently? Would something like this work?

let dst_addr: u64 = 0x1000;
let src = SomeData {a: 1, b: 2, c: 3, d: 4};
unsafe {
    let tmp: &[u8; 10] = transmute(src);
    copy(dst_addr as *mut _, tmp);
}

Please note that the repr(C, packed) part is actually needed here.

The software is running on bare x86_64, ring 0, without operating system or other limitations. Also, I'm programming without the standard library, so this should be achievable with only the core library.

This is, of course, unsafe, but it is not a problem.

Edit: Just clarifying: I'm copying to uninitialized memory.


Solution

  • You will want to have a look at the core::ptr module.

    Its write function does exactly what you wish:

    pub unsafe fn write<T>(dst: *mut T, src: T)
    
    core::ptr::write(dst_addr as *mut_, src);
    

    As noted, it does not drop the value current at dst_addr (you can use read to do so).

    I advise against using intrinsics::copy_nonoverlapping as intrinsics will never be stabilized.