Providing pointer to CString

I have a ffi function that expects *mut char:

let c_string = CString::new("Very long long string").expect("CString::new failed");
    let raw: *mut c_char = c_string.into_raw();

And then call:

         &mut raw,

The problem I'm having with that even though it apparently works that the "raw" argument is passed for the reason that the calling function will write something into it. How can I know (I can't) how much space should I allocate (i.e how long the string should be)?

You don't have to allocate anything. The whole point of passing in the pointer itself by reference is that the function will allocate and set the out pointer to the allocated string. Consequently, your current code leaks memory.

1 Like

Thanks, that is exactly the answer I was looking for.

Would something like that be OK?

No, you don't need that (it also leaks memory because there is always a null terminator). Just create a null pointer and pass that in. The function overwrites the pointer itself, not the buffer it points to. let mut raw: *mut c_char = std::ptr::null_mut(); will do the trick.

OK, now I am confused :slight_smile: . How am I supposed to create that ptr?
Like that?
let raw: *mut c_char ;

Check my edit.

Thanks. Really appreciate it.

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.