watzon
watzon

Reputation: 2549

How would you go about creating a pointer to a specific memory address in Rust?

For example, let's say I want to access whatever value is stored at 0x0900. I found the function std::ptr::read in the Rust standard library, but the documentation isn't super clear on how to use it and I'm not sure if it's the right way.

This is what I've tried:

use std::ptr;

fn main() {
    let n = ptr::read("0x0900");
    println!("{}", n);
}

but it gives me error E0277

Upvotes: 6

Views: 5185

Answers (1)

fjh
fjh

Reputation: 13081

If you want to read a value of type u32 from memory location 0x0900, you could do it as follows:

use std::ptr;

fn main() {
    let p = 0x0900 as *const u32;
    let n = unsafe { ptr::read(p) };

    println!("{}", n);
}

Note that you need to decide what type of pointer you want when casting the address to a pointer.

Upvotes: 14

Related Questions