A C string is a contiguous sequence of platform-specific character types ending with a null character. Rust can borrow this memory instead of allocating a second string. section 3.2.2
When reading a null-terminated string from C:
- Use CStr to represent the borrowed C string without taking ownership of C-managed memory. section 3.2.2
- Convert it to a Rust string slice with to_str, which validates UTF-8 and reports invalid input. section 3.2.2
- Keep the conversion read-only when the Rust code only needs to inspect the C buffer. section 3.2.2
Borrowing a C input line
A C function passes line as *const c_char. Rust checks for a null pointer, constructs CStr::from_ptr(line) inside unsafe code, and converts it with c_str.to_str(). The resulting slice points at the same address as the original C buffer. section 3.2.2
use libc::{c_char, c_int};
use std::ffi::CStr;
#[no_mangle]
pub extern "C" fn solve(
line: *const c_char, solution: *mut c_int) -> c_int {
if line.is_null() || solution.is_null() {
return 1;
}
let c_str = unsafe { CStr::from_ptr(line) }; #1
let r_str = match c_str.to_str() { #2
Ok(s) => s,
Err(e) => {
eprintln!("UTF-8 Error: {}", e);
return 1;
},
};
println!("line: {}", r_str);
unsafe {
*solution = 1024;
}
0
}
Inspect the complete FFI function that checks pointers, borrows a null-terminated C string, validates UTF-8, and prints the resulting slice. section 3.2.2
