Thomas Braun
Thomas Braun

Reputation: 535

Getting pointer by &str

Consider this pseudocode:

    let k = 10;
    let ptr = &k as *const k;
    println!("{:p}", ptr); // prints address of pointer
    let addr = format!("{:p}", ptr);

    super-unsafe {
    // this would obviously be super unsafe. It may even cause a STATUS_ACCESS_VIOLATION if you try getting memory from a page that the OS didn't allocate to the program!

    let ptr_gen = PointerFactory::from_str(addr.as_str()); 

    assert_eq!(k, *ptr_gen);
    }

The pseudocode gets the idea across: I want to be able to get a pointer to a certain memory address by its &str representation. Is this... possible?

Upvotes: 0

Views: 1024

Answers (1)

Peter Varo
Peter Varo

Reputation: 12150

So essentially what you want to do is parse the string back to an integer (usize) and then interpret that value as a pointer/reference:

fn main()
{
    let i = 12i32;
    let r = format!("{:p}", &i);


    let x = unsafe
    {
        let r = r.trim_start_matches("0x");
        &*(usize::from_str_radix(&r, 16).unwrap() as *const i32)
    };

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

You can try this yourself in the playground.

As you can see, you don't even need to cast your reference into a raw pointer, the {:p} formatter takes care of representing it as a memory location (index).


Update: As E_net4 mentioned this in the comment section, it is better to use usize here, which is architecture defined unlike the machine sized one. The transmute was not necessary, so I removed it. The third point about undefined behaviour however seems obvious to whomever tries to do something like the above. This answer provides a way to achieve what the OP asked for which doesn't mean this should be used for anything else than academic/experimental purposes :)

Upvotes: 1

Related Questions