Home > Enterprise >  Convert pointer address to original instance
Convert pointer address to original instance

Time:07-07

If I get an address of a pointer in Rust and convert it to a numeric type, for example like this:

let map: HashMap<i32, String> = HashMap::new();
let ptr = std::ptr::addr_of!(map); 
let ptri = ptr as i32;

Can I get back the original instance (HashMap in that case) from ptri variable?

Something like in C:

HashMap *map = (HashMap*)(uintptr_t)ptri;

CodePudding user response:

Only if you are on a 32-bit machine. Otherwise, the cast of the pointer to an i32 will truncate, and you won't be able to get the original address back. Switching to use an isize to handle pointer-sized integers instead, you can cast the pointer back to the HashMap type, dereference it, then borrow that instance of the hash map:

use std::collections::HashMap;

fn main() {
    let map: HashMap<i32, String> = HashMap::new();
    let ptr = std::ptr::addr_of!(map);
    let ptri = ptr as isize;

    println!("{:?}", map);
    println!("{:?}", ptr);
    println!("{:?}", ptri);
    println!("{:?}", unsafe {
        &*(ptri as *const HashMap<i32, String>)
    });
}
  • Related