Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUST

armanriazi•rust•unsafe•rawpointer

Unsafe Rust has two new types called raw pointers that are similar to references. As with references, raw pointers can be immutable or mutable and are written as *const T and *mut T, respectively. The asterisk isn’t the dereference operator; it’s part of the type name. In the context of raw pointers, immutable means that the pointer can’t be directly assigned to after being dereferenced.
    let mut num = 5;
    let r1 = &num as *const i32;
    let r2 = &mut num as *mut i32;
Notice that we don’t include the unsafe keyword in this code. We can create raw pointers in safe code; we just can’t dereference raw pointers outside an unsafe block, as you’ll see in a bit.    
    unsafe {
        println!("r1 is: {}", *r1);
        println!("r2 is: {}", *r2);
    }

   let address = 0x012345usize;
   let r = address as *const i32;
   
Creating a raw pointer to an arbitrary memory address
 
PREVIOUS NEXT
Tagged:
ADD COMMENT
Topic
Name
8+2 =