[英]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.我是 Rust 的新手,我正在努力将我的 Rust 代码与 C 库连接起来。 The library expects a raw pointer *f32
to the memory buffer of size 3*N.该库需要一个指向大小为 3*N 的内存缓冲区的原始指针*f32
。 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?在 Rust 代码中,我有一个大小为 N 的数组Vec<[f32;3]>
。如何从该数组中获取*mut f32
类型的原始指针?
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:我尝试coords.as_mut_ptr()
但由于类型不匹配而无法正常工作:
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.所以我需要“展平”数据,将其视为指向平面 f32 缓冲区的指针。 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
指向N * 3
元素的布局与*mut [f32; 3]
相同。 *mut [f32; 3]
of N
elements. *mut [f32; 3]
N
个元素。 Therefore, you can just cast()
:因此,您可以cast()
:
let ptr: *mut f32 = coords.as_mut_ptr().cast::<f32>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.