Answer#
Two differences cause nearly all the trouble. A C string ends at the first zero byte, so it cannot contain one. A Rust String or &str can contain a zero byte, has an explicit length, and must be valid UTF-8. A char * from C can hold any bytes: text in Windows-1252, Latin-1 or a binary blob.
| Role | Type | Notes |
|---|---|---|
| Owned C string that Rust creates and lends to C | CString | Adds the trailing zero byte; fails if the text has a zero byte inside |
| Borrowed C string that C gave to Rust | &CStr | Created from a raw pointer with unsafe; does not own the memory |
| Rust text | String, &str | UTF-8 |
| Bytes of unknown encoding | Vec<u8>, &[u8] | Use when the data is not guaranteed to be text |
| Operating system names (files, environment) | OsString, &OsStr | Not always valid UTF-8 |
The program creates a CString, calls C's strlen (which every Rust program on this target already links through the C runtime), and reads text back with the checked and the lossy conversions. It was compiled and run with rustc 1.93.0.
use std::ffi::{c_char, CStr, CString};
extern "C" {
fn strlen(s: *const c_char) -> usize;
}
fn c_len(s: &str) -> Result<usize, std::ffi::NulError> {
let c = CString::new(s)?; // adds the trailing NUL, refuses interior NULs
// SAFETY: `c` is a valid NUL-terminated string that lives until the end of this function.
Ok(unsafe { strlen(c.as_ptr()) })
}
fn main() {
println!("{:?}", c_len("hello"));
println!("{:?}", c_len("h\0llo").map_err(|e| e.to_string()));
println!("{:?}", c_len("naïve"));
let from_c: &CStr = c"bytes from C";
println!("{} {:?}", from_c.to_str().unwrap(), from_c.to_bytes_with_nul().len());
let bad = CStr::from_bytes_with_nul(b"caf\xe9\0").unwrap();
println!("{:?} {}", bad.to_str().is_err(), bad.to_string_lossy().escape_default());
}Ok(5)
Err("nul byte found in provided data at position: 1")
Ok(6)
bytes from C 13
true caf\u{fffd}Three results to notice. strlen returns 6 for "naïve" because C counts bytes, and ï takes two bytes in UTF-8. The text with a zero inside is refused by CString::new, so C never sees a silently shortened string. The last line holds Windows-1252 bytes (0xE9 is é there): they are not valid UTF-8, to_str fails, and to_string_lossy replaces the bad byte with U+FFFD, printed here as an escape.
How to do it#
- Inside the Rust part of the program, keep text as
Stringand&str. Convert only at the boundary. - To pass a string to C: build a
CString, keep it alive for as long as C uses the pointer, and pass.as_ptr(). A common bug isCString::new(x).unwrap().as_ptr(), where theCStringis dropped at the end of the statement and C gets a dangling pointer. - To read a string from C: check for null, then
unsafe { CStr::from_ptr(p) }, then decide:to_str()if invalid text should be an error,to_string_lossy()if you accept replacement characters,to_bytes()if the encoding is not UTF-8 (then decode it, see the thread on non-UTF-8 text). - For a string that C will keep or free, agree on who frees it (see the thread on calling Rust from Python with ctypes).
Common mistakes#
- Casting a
&strpointer to*const c_char. A&strhas no trailing zero byte, so C reads past the end. - Assuming a
char *from C is UTF-8. On Windows, strings from the C runtime may use the system code page. - Using
to_string_lossyon data you then write back: the replacement changes the bytes.
Related questions#
What does the c"..." literal do?#
It makes a &CStr with the trailing zero byte included, checked at compile time (the from_c line above uses it, with rustc 1.93.0).
Do I still need strlen from C?#
No. CStr::to_bytes().len() and str::len() do the job. The call above only shows how a C function is declared and called.
Sources#
std::ffi::CStr: https://doc.rust-lang.org/std/ffi/struct.CStr.htmlstd::ffi::CString: https://doc.rust-lang.org/std/ffi/struct.CString.html- The Rustonomicon, "Foreign Function Interface": https://doc.rust-lang.org/nomicon/ffi.html