简体   繁体   中英

How to get a raw pointer *mut f32 from a rust vector Vec<[f32;3]>?

I'm new to rust and I'm struggling to connect my rust code with a C library. The library expects a raw pointer *f32 to the memory buffer of size 3*N. In rust code I have an array Vec<[f32;3]> of size N. How can I get a raw pointer of type *mut f32 from this array?

let coords: Vec<[f32;3]> = vec![[0.0,0.0,0.0]; N];
// Call a wrapper of C function expecting a raw pointer *mut f32
wrapped_c_function(coords.????, 3*N);

I tried coords.as_mut_ptr() but it doesn't work because of the type mismatch:

mismatched types
expected raw pointer `*mut f32`
   found raw pointer `*mut [f32; 3]`

So I need to "flatten" the data to be treated as a pointer to flat f32 buffer. What is the correct way of doing this?

Because arrays are flat in memory, the layout of a pointer *mut f32 to N * 3 elements is the same as of *mut [f32; 3] *mut [f32; 3] of N elements. Therefore, you can just cast() :

let ptr: *mut f32 = coords.as_mut_ptr().cast::<f32>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM