Best practice for returning Rust-generated string to C/C++ caller

I'm writing a small library in Rust which is to be consumed by a larger C++ host application. One of the functions written in Rust needs to return a string (UTF-8) value. The size of this response could be arbitrarily large and is not known prior to the call, so preallocating a buffer is not a viable solution.

I'm looking for best practices to ensure that any memory allocated for that string is properly deallocated when the C++ application is done with it.

I'm using cbindgen, but the docs don't seem to address that question. The API surface is small enough that I could manually build headers if that works better.

Thanks!

If rust is allocating the memory, rust has to deallocate the memory. So you'll need to provide a free function with your C API that does the deallocation, and document that your C++ callers need to call that function when they're done with your object.

Edit: If you're passing a pointer over the C API, it may be enough to accept that pointer back, and do Box::from_raw(ptr). Then the lifetime checker knows the object is owned by the free function and calls Drop::drop on it at the end of the function.

Something like:

#[no_mangle]
pub unsafe extern fn scouten_free(scouten_ptr: *mut scouten) {
    Box::from_raw(scouten_ptr);
}

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.