Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 669
watzon Avatar asked Feb 09 '16 01:02

watzon


1 Answers

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.

like image 130
fjh Avatar answered Sep 23 '22 06:09

fjh