Rust Reference ยท Strings and Text
Rust CString and CStr
Reference for Rust CString and CStr: NUL-terminated strings for C interop, c"" literals, NulError, from_bytes_with_nul, to_str and calling C functions.
C functions expect strings that end with a zero byte and contain no zero byte anywhere else. Rust strings are different: they store their length, may contain \0, and have no terminator. CString is the owned, NUL-terminated string you build in Rust to hand to C, and CStr is the borrowed view (like String and str) used to read a string that C gave you.
Creating a CString checks for interior zero bytes and appends the terminator. Since Rust 1.77 you can also write a C string literal, c"hello", which is a &CStr checked at compile time. Neither type promises UTF-8: C strings are just bytes.
use std::ffi::CString; let name = CString::new("Ada").unwrap();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
fn CString::new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> fn CStr::as_ptr(&self) -> *const c_char fn CString::into_string(self) -> Result<String, IntoStringError> unsafe fn CStr::from_ptr<'a>(ptr: *const c_char) -> &'a CStr fn CStr::from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> fn CStr::from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError> fn CStr::to_str(&self) -> Result<&str, Utf8Error> fn CStr::to_string_lossy(&self) -> Cow<'_, str>
| Name | Description |
|---|---|
t |
Bytes or text that become the string body. A trailing zero is added for you. |
ptr |
A pointer to a NUL-terminated string. |
bytes |
A byte slice that contains the string; from_bytes_with_nul needs exactly one zero, at the end. |
Returns: CString::new returns Err(NulError) if the input contains a zero byte; the error exposes nul_position() and into_vec(). to_str fails with Utf8Error for non-UTF-8 content.
Errors / panics / edge cases: from_ptr is unsafe: the pointer must be non-null, valid until the first zero byte, and the memory must not change while the &CStr lives. Passing a dangling or unterminated pointer is undefined behavior.
Usage notes
- Keep the
CStringalive.CString::new("x").unwrap().as_ptr()creates a temporary that is dropped at the end of the statement, leaving a dangling pointer. Bind it to a variable first. as_ptr()gives a borrowed pointer. Useinto_raw()to give ownership to C, and take it back withCString::from_rawto free it exactly once. Never pass this pointer to C'sfree.- The terminator is not counted.
count_bytes()andas_bytes()leave it out;as_bytes_with_nul()includes it. c_charisi8oru8depending on the platform. Usestd::ffi::c_charrather than a hard-coded type.- Edition 2024 requires
unsafe externfor blocks that declare foreign functions; calling them still needsunsafe. - Lossy decoding with
to_string_lossyis the right default for printing data you do not control. - For file paths use
PathandOsStr, and convert withOsStrExt::as_byteson Unix before making aCString. - Cost:
newcopies the bytes once and scans for zero bytes.
Related
OsStringandOsStr,from_utf8,as_bytes,String- Lessons: Strings, Strings overview