Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: How to pass an uninitialized data to a function which takes a &mut [T]?
I'm trying to figure out the right way to pass an uninitialized array to an external function which fills some of its elements and returns the number of elements that were initialized.
Is the following code correct? Is there a better way to achieve this on stable Rust? I checked with miri and it does not seem to complain but slice
is a reference to uninitialized data so I'm suspicious. If this is correct - what is the safety reasoning for the line which binds slice
? If not correct - what is the right way to do it?
Thanks
use std::mem::MaybeUninit;
/// Fills the buffer with data, returns the number of elements written. This is just an example for a 3rd party crate function (maybe some FFI wrapper).
unsafe fn InsertStuffInBuffer(buf: &mut [u16]) -> usize;
fn main() {
let mut buf = MaybeUninit::<[u16; 260]>::uninit();
let slice = unsafe { std::slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut u16, 260) };
let len = unsafe { InsertStuffInBuffer(slice) };
let buf = unsafe { std::slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut u16, len) };
println!("{:?}", buf);
}
3 posts - 3 participants
🏷️ Rust_feed