5

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.

2
  • 3
    Why would you want to do this? Pointers are not as useful in Rust as they are in C. If you explain why you want this, then maybe someone can give you a better, more idiomatic Rust way of doing whatever you want to do. Commented Oct 12, 2020 at 7:07
  • 1
    @Jesper thank you for the concern on safety while programming in Rust. I need this to talk with C, specially on a OpenGL binding for Rust. Yes I could use glutin which is safe. Indeed I already use it, but I'm writing one in pure OpenGL C calls to compare with glutin and also support external textures (which I believe is not possible with glutin) Commented Oct 13, 2020 at 21:39

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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

1 Comment

FWIW C arrays are also "sequences of objects", they decay to pointers, but they are not in and of themselves pointers. IIRC interacting with C arrays is weird and inconsistent because of backwards compatibility with BCPL, where an array actually was a pointer to a separate location. If C arrays were actually pointers, flexible array members would not be a thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.