Sub topic 4
Passing strings with CString and CStr
This chapter assumes you can write basic Rust, can read a declaration like unsafe extern "C" { fn strlen(...) }, and know what *const c_char means. The examples need Rust 1.82 or newer for unsafe extern blocks.
Why Rust strings don't fit C
A C string is a pointer to bytes that ends with a zero byte (the nul terminator). The function finds the end by scanning for that zero. A Rust &str is different in three ways:
- It stores a pointer and a length, with no terminator.
- It may contain zero bytes in the middle.
- It is always valid UTF-8, while C strings can hold any bytes.
Passing s.as_ptr() from a &str to C is a bug. C would read past the end of the data looking for a zero. Rust provides two types in std::ffi to cross this gap.
| Type | Owns data? | Think of it as | Direction |
|---|---|---|---|
| `CString` | Yes | `String` for C | Rust to C |
| `CStr` | No (borrowed) | `&str` for C | C to Rust, or a view of a `CString` |
Sending a string to C with CString
CString::new copies your bytes and appends the terminator. It returns an error if the input contains an interior zero byte, because C would treat that zero as the end of the string. as_ptr() gives the *const c_char that C expects.
use std::ffi::{c_char, CString, NulError};
unsafe extern "C" {
fn strlen(s: *const c_char) -> usize;
}
fn c_length(text: &str) -> Result<usize, NulError> {
let c = CString::new(text)?;
Ok(unsafe { strlen(c.as_ptr()) })
}
fn main() {
println!("{:?}", c_length("hello"));
println!("{}", c_length("he\0llo").is_err());
}This prints Ok(5) and then true.
The dangling pointer trap
as_ptr() borrows from the CString. It does not keep the CString alive. This line compiles but is wrong:
let p = CString::new("hi").unwrap().as_ptr();The temporary CString is dropped at the end of the statement, so p points at freed memory. Bind the CString to a variable that lives past the C call, as c does above.
Reading a string from C with CStr
When C returns a *const c_char, wrap it with CStr::from_ptr. This function is unsafe because you promise three things:
- The pointer is non-null.
- It points to a terminated string.
- The memory stays valid and unmodified while the
CStrexists.
CStr only borrows. It never frees the memory. Whether you must free the original pointer is an ownership question, covered in a later chapter.
use std::ffi::{c_char, CStr, CString};
unsafe extern "C" {
fn getenv(name: *const c_char) -> *const c_char;
}
fn env_var(name: &str) -> Option<String> {
let name = CString::new(name).ok()?;
let ptr = unsafe { getenv(name.as_ptr()) };
if ptr.is_null() {
return None;
}
let value = unsafe { CStr::from_ptr(ptr) };
Some(value.to_string_lossy().into_owned())
}
fn main() {
println!("{:?}", env_var("HOME"));
}getenv returns null when the variable is missing, so the code checks for null before calling from_ptr. The result is copied into an owned String, because the C memory may change later.
Converting a CStr to Rust text
A CStr can hold bytes that are not UTF-8, so conversion has two options:
to_str()returnsResult<&str, Utf8Error>. Use it when invalid text should be an error.to_string_lossy()returns aCow<str>and replaces invalid bytes withU+FFFD. Use it when you only need something printable.
For a fixed string in your own code, a C-string literal such as c"hello" (Rust 1.77 and newer) produces a &CStr with the terminator already in place. It needs no allocation and no error handling.
Common mistakes
- Calling
.unwrap()onCString::newfor user input. An interior zero byte makes it fail, so return the error instead. - Passing
as_ptr()of a temporaryCString. - Calling
CStr::from_ptron a null pointer. - Assuming C text is UTF-8.
Exercise
A colleague writes let p = CString::new(name).unwrap().as_ptr(); unsafe { c_function(p) };. Why is this undefined behavior, and how do you fix it?
Show answer
The temporary CString is dropped at the end of the first statement, so p dangles when c_function runs. Store the CString in a variable first, as in let c = CString::new(name).unwrap();, then call c_function(c.as_ptr()) while c is still in scope. Returning an error instead of calling unwrap() is also better when name may contain a zero byte.