Search code examples
rustffi

Is CString more expensive than creating a CStr?


I'm creating some C bindings in rust and some of the functions require *const c_char as an argument, but I don't know how it should be done in the most efficient way, does CString::new() create an allocation that CStr can avoid?

extern "C" fn foo(string: *const c_char) {
    // this function does not modify the string
}

fn main() {
    let arg = CString::new("hello").expect("error");
    unsafe { foo(&arg.as_ptr()) }
    // or
    let arg = CStr::from_bytes_with_nul(b"hello\0").expect("error");
    unsafe { foo(arg.as_ptr()) }
}

Solution

  • thanks to everyone's comments I can conclude that CStr, like str, avoids an allocation but we can only use it when we know the value of the string at compile time, if the string is created during execution we need to use CString