Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Rust array to pointer?

Tags:

rust

I couldn't find a simple thing on google. How to convert a simple Rust array to a pointer?

How to get pointer to [u8; 3]? I tried doing as *mut u8 but it wouldn't work.

like image 609
Guerlando OCs Avatar asked Oct 23 '25 06:10

Guerlando OCs


2 Answers

Use as_ptr() or as_mut_ptr().

fn main() {
    let a: [u8; 3] = [1, 2, 3];
    println!("{:p}", a.as_ptr());
}
0x7ffc97350edd

Arrays coerce to slices, so any slice method may be called on an array.

like image 172
kmdreko Avatar answered Oct 24 '25 20:10

kmdreko


Note that arrays in Rust are just blobs of memory. They does not point on some stored objects, like an arrays in C do, they are a sequence of objects.

If you have some data and want to get a pointer to it, you'll usually create a reference instead, since only references (and other pointers) can be cast to pointers with as:

fn main() {
    let a: [u8; 3] = [1, 2, 3]; // a blob of data on the stack...
    let a_ref = &a; // a shared reference to this data...
    let a_ptr = a_ref as *const u8; // and a pointer, created from the reference
    println!("{:p}", a_ptr);
}

Playground

like image 40
Cerberus Avatar answered Oct 24 '25 20:10

Cerberus