There's a lot of questions and examples out there of either creating a Rust string to FFI or recreating a Rust string from an FFI pointer. However, there are just a few examples of
allocating a buffer on the Rust side and passing a pointer to it to FFI.
So far the recommended ways seems to be:
let v = vec![0; size];
let s = CString::from_vec_unchecked(v);
let ptr = s.into_raw();
let err = call_to_ffi(ptr, size);
assert_eq!(err, 0);
let s = CString::from_raw(ptr);
Is it safe to replace vec![0;size]
with Vec::<u8>::with_capacity(size)
. With the latter, the vector will be uninitialized, but the FFI function will fill it in anyway.
Actually, I might even get by without a CString before FFI:
let mut v = Vec::<u8>::with_capacity(size);
let ptr = v.as_mut_ptr() as *mut i8;
call_to_ffi(ptr, size)
let s = unsafe {CString::from_raw(ptr)}
Is this safe?
What is the most performant way compared to C's ?:
char * buf = (char *) malloc(num);