FAQ - Help and questions

How do C strings (char*, NUL-terminated) map to CStr, CString and &str?

#porting#c-language#stringspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A C string is bytes ending in a zero byte, with no encoding. Rust's str is UTF-8 with a length and no terminator. At a boundary use CString to give C a string, CStr to read one from C, and to_str or to_string_lossy to get a Rust str, handling text that is not valid UTF-8.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

RoleTypeNotes
Owned C string that Rust creates and lends to CCStringAdds the trailing zero byte; fails if the text has a zero byte inside
Borrowed C string that C gave to Rust&CStrCreated from a raw pointer with unsafe; does not own the memory
Rust textString, &strUTF-8
Bytes of unknown encodingVec<u8>, &[u8]Use when the data is not guaranteed to be text
Operating system names (files, environment)OsString, &OsStrNot 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.

src/main.rsrust
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());
}
text
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#

  1. Inside the Rust part of the program, keep text as String and &str. Convert only at the boundary.
  2. 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 is CString::new(x).unwrap().as_ptr(), where the CString is dropped at the end of the statement and C gets a dangling pointer.
  3. 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).
  4. 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 &str pointer to *const c_char. A &str has 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_lossy on data you then write back: the replacement changes the bytes.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet