I cannot seem to find an easy way to copy bytes into a c_char array needed for a FFI. The following code (playground) fails to compile, because c_char is i8, but b"..." turns into u8:
The most idiomatic solution without using other crates (Which I'm omitting due to my unfamiliarity with this in the crate ecosystem) would be as follows:
fn main() {
let mut c_char_array: [std::os::raw::c_char; 16] = [0; 16];
for (dest, src) in c_char_array.iter_mut().zip(b"hello, world\0".iter()) {
*dest = *src as _;
}
}
It seems you're dealing with C Strings, which Rust can deal with using std::ffi::CString.
If you want to use unsafe, perhaps the following?
let mut c_char_array: [std::os::raw::c_char; 16] = [0; 16];
unsafe {
*(&mut c_char_array as *mut _ as *mut [u8; 13]) = *b"hello, world\0";
}
Thanks, I already thought about the iterator for loop approach, but would have guessed that there is an even easier way.
I had also tried std::ffi:{CStr,CString} before, but they also turn into [u8], so they have the same issue as my initial code.
The [c_char] buffer is part of a larger data struct in a C library that users of the C library are usually initialise by copying bytes into via memcpy and friends.