#How to allocate blank cStrings for FFI

6 messages · Page 1 of 1 (latest)

potent turret
#

I'm writing some code that interacts with a c ffi. I need to wrap a c function in the form of:
void c_function (char * res, int max_len);, where the function will fill res with up to max_len-1 bytes of data, plus a terminator. I would like the rust wrapper to return a Result<String, Error> .

I'm trying to create the empty buffer to pass in to the function but I'm having difficulty. I read the docs for std::ffi::CString, but there is nothing close to the with_capacity I was hoping for. My closest attempt is CString::from_vec_unchecked(vec![0; max_len]), but this is unsafe for reasons I do not understand.

What is the best way to allocate a buffer I can pass as a *mut c_char?

#

It's occurred to me that a Vec<u8> might be enough, as I can just pass the result into String::from_utf8. Testing this.

lyric hamlet
#

Yeah you will want to use a Vec for the buffer then convert that into a CString after

potent turret
#

Cool, thanks

lyric hamlet
# potent turret Cool, thanks

Oh also double check if the function includes the null byte in the max size length or if your buffer needs to be one larger. And also if it actually puts a null byte at the end instead of like returning a length somewhere

potent turret
#

It's frustratingly vague. From the docs:

Description

Returns an ASCII string identifying the device dev in the NULL-terminated string pointed to by name. len specifies the maximum length of the string that may be returned.

My gut is to read that as the string with the null terminator will be <= max_len, but it's weird enough I'll add an extra byte to be safe