Struct bitflags::__core::ffi::CString [] [src]

pub struct CString {
    // some fields omitted
}
1.0.0
[]

A type representing an owned C-compatible string

This type serves the primary purpose of being able to safely generate a C-compatible string from a Rust byte slice or vector. An instance of this type is a static guarantee that the underlying bytes contain no interior 0 bytes and the final byte is 0.

A CString is created from either a byte slice or a byte vector. After being created, a CString predominately inherits all of its methods from the Deref implementation to [c_char]. Note that the underlying array is represented as an array of c_char as opposed to u8. A u8 slice can be obtained with the as_bytes method. Slices produced from a CString do not contain the trailing nul terminator unless otherwise specified.

Examples

use std::ffi::CString;
use std::os::raw::c_char;

extern {
    fn my_printer(s: *const c_char);
}

let c_to_print = CString::new("Hello, world!").unwrap();
unsafe {
    my_printer(c_to_print.as_ptr());
}

Safety

CString is intended for working with traditional C-style strings (a sequence of non-null bytes terminated by a single null byte); the primary use case for these kinds of strings is interoperating with C-like code. Often you will need to transfer ownership to/from that external code. It is strongly recommended that you thoroughly read through the documentation of CString before use, as improper ownership management of CString instances can lead to invalid memory accesses, memory leaks, and other memory errors.