How to retrieve a pointer to a slice of a vector?

Hi,

Let assume I need to send a vector form one program to another. The way I am doing it right now is :

let v : Vec<i32> = vec![5i32; 10]

fn myfunction (
    v.as_ptr(), // pointer to my vec 
    10            // its length
)

But how would I do the same for a vector slice? do I need to make a copy of v and then repeat the procedure or can I say something like:

fm my function (
    v[4].as_ptr()  // so I want to send a slice starting at 4 of length 4
    4
)

Any advice ?

thank you :slight_smile:

Between processes? Or just between an FFI boundary?
If it's the latter, then you're doing it correctly.

It's just a slice, which you would have as a reference:

let x = vec![1, 2, 3];
let y = &x[1..];
let ptr = y.as_ptr();

Then, that pointer will simply point to the data; and you (The programmer, not the compiler) should operate under the constraint that ptr points to something with the lifetime of x. You don't need to copy anything:

fn foreign_takes_slice(ptr: *const T, len: u32);
let slice = &x[1..];
foreign_takes_slice(
    slice.as_ptr() as *const _,
    slice.len() as _,
);

You could also do it in the c-fashion and take a reference to a single item and pass the pointer to that as you did in your second example:

fn foreign_takes_slice(ptr: *const T, len: u32);
foreign_takes_slice(
    &v[4] as *const _,
    (v.len() - 4) as _,
);
1 Like

I think the second one should say &v[4].

1 Like

To be sure future compiler versions don't define your code to have UB, you should use v[4..].as_ptr() instead of &v[4] as *const _ (see https://github.com/BurntSushi/rust-memchr/issues/58).

2 Likes