On this page
CString
Prev: ffi | Up: ffi | Next: `extern_C`
Rel: ffi, rust/builtins
Ref: Rust std — CString
Tags: #public #prog #rust #stdlib #ffi #tier/specialized
Signature & Overview
CString (owned) | &CStr (borrowed)
NUL-terminated byte strings without interior NUL bytes for exchanging strings across the C ABI.
Notes & Pitfalls
- Rejects interior NUL (
\0) bytes:CString::new()returnsErr(NulError)so C strings are guaranteed properly terminated. - Keep the
CStringalive while using.as_ptr(): CallingCString::new("hi").unwrap().as_ptr()in one expression creates a dangling pointer immediately!
Example
use std::ffi::{CStr, CString};
fn main() {
let c_str = CString::new("hello ffi").expect("no interior NUL");
let borrowed: &CStr = c_str.as_c_str();
assert_eq!(borrowed.to_str().unwrap(), "hello ffi");
}
Linked from
Related notes
- tuts/rust/std/ffi/extern_C Linked here; links to this page; shared tags: #ffi, #prog, #rust, #stdlib, #tier
- tuts/rust/std/ffi Linked here; links to this page; shared tags: #ffi, #prog, #rust, #stdlib
- tuts/rust/builtins Linked here; shared tags: #prog, #rust
- tuts/rust/std/collections/BinaryHeap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/BTreeMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashSet shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/VecDeque shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/Display shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/Error shared tags: #prog, #rust, #stdlib, #tier