Using libc read and write


I am trying to use libc's read and write functions and the buffers are of type c_void. How do I convert a string or array in Rust to c_void?

If you have an &[u8], you can call slice.as_ptr() to obtain a raw pointer of type *const u8. Then you can cast it to an *const c_void.

use std::ffi::c_void;

let ptr = slice.as_ptr() as *const c_void;

With a &str, first call as_bytes() to convert it to a &[u8].

When reading, you should use as_mut_ptr instead to get a pointer through which mutation is allowed.

You should probably use the nix::unistd::read and nix::unistd::write methods from nix crate. These are safe, unlike the methods from the libc crate.


Note also that reading through the pointer into string is unsafe - if the bytes written are not valid UTF-8, this will be UB.

Yeah, always read into a byte array, then convert to a string.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.