How to write a slice into a file?

Viewed 187

I have code which interracts with C via bindings. In it I have this:

let a1: *const i8 = get_data();
let size1 = get_size_of_data();

let a2 = ::std::slice::from_raw_parts(a2, size1);

I need to write data to which a1 points. Or a2 as a slice. The size or length of the data is known.

I tried:

  let mut f1 = File::create("my_file.dat").unwrap();
  // ??? f1.write_all(a2).expect("unable to write binary data to file");
  // ??? f1.write_all(a2.as_bytes).expect("unable to write binary data to file");

and nothing has compiled.

How to do it?

1 Answers

You need pass a &[u8] to write_all, but you have a &[i8]. So, the only change you need is to cast your *const i8 to a *const u8 in slice::from_raw_parts

let a1: *const i8 = std::ptr::null(); // replace with `get_data()`
let size1 = 42; // replace `get_size_of_data()`

let a2: &[u8] = unsafe { std::slice::from_raw_parts(a1 as *const u8, size1) };

use std::io::Write;
let mut f1 = std::fs::File::create("my_file.dat").unwrap();
f1.write_all(a2).expect("write must succeed");
Related