std::ffi::CString - Rust
Description: API documentation for the Rust `CString` struct in crate `std`.
Keywords: rust, rustlang, rust-lang, CString

# Struct std::ffi::CString 1.0.0 [−] [src]

    pub struct CString { /* fields omitted */ }

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());
    }Run

# 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.

## Methods

### `impl CString`
[src]

#### `fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError>`

Creates a new C-compatible string from a container of bytes.

This method will consume the provided data and use the underlying bytes to construct a new string, ensuring that there is a trailing 0 byte.

# Examples

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

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

    let to_print = CString::new("Hello!").unwrap();
    unsafe {
        puts(to_print.as_ptr());
    }Run

# Errors

This function will return an error if the bytes yielded contain an internal 0 byte. The error returned will contain the bytes as well as the position of the nul byte.

#### `unsafe fn from_vec_unchecked(v: Vec<u8>) -> CString`

Creates a C-compatible string from a byte vector without checking for interior 0 bytes.

This method is equivalent to `new` except that no runtime assertion is made that `v` contains no 0 bytes, and it requires an actual byte vector, not anything that can be converted to one with Into.

# Examples

    use std::ffi::CString;

    let raw = b"foo".to_vec();
    unsafe {
        let c_string = CString::from_vec_unchecked(raw);
    }Run

#### `unsafe fn from_raw(ptr: *mut c_char) -> CString`
1.4.0

Retakes ownership of a `CString` that was transferred to C.

Additionally, the length of the string will be recalculated from the pointer.

# Safety

This should only ever be called with a pointer that was earlier obtained by calling `into_raw` on a `CString`. Other usage (e.g. trying to take ownership of a string that was allocated by foreign code) is likely to lead to undefined behavior or allocator corruption.

#### `fn into_raw(self) -> *mut c_char`
1.4.0

Transfers ownership of the string to a C caller.

The pointer must be returned to Rust and reconstituted using `from_raw` to be properly deallocated. Specifically, one should not use the standard C `free` function to deallocate this string.

Failure to call `from_raw` will lead to a memory leak.

#### `fn into_string(self) -> Result<String, IntoStringError>`
1.7.0

Converts the `CString` into a `String` if it contains valid Unicode data.

On failure, ownership of the original `CString` is returned.

#### `fn into_bytes(self) -> Vec<u8>`
1.7.0

Returns the underlying byte buffer.

The returned buffer does not contain the trailing nul separator and it is guaranteed to not have any interior nul bytes.

#### `fn into_bytes_with_nul(self) -> Vec<u8>`
1.7.0

Equivalent to the `into_bytes` function except that the returned vector includes the trailing nul byte.

#### `fn as_bytes(&self) -> &[u8]`

Returns the contents of this `CString` as a slice of bytes.

The returned slice does not contain the trailing nul separator and it is guaranteed to not have any interior nul bytes.

#### `fn as_bytes_with_nul(&self) -> &[u8]`

Equivalent to the `as_bytes` function except that the returned slice includes the trailing nul byte.

## Methods from Deref<Target=CStr>

#### `fn as_ptr(&self) -> *const c_char`

Returns the inner pointer to this C string.

The returned pointer will be valid for as long as `self` is and points to a contiguous region of memory terminated with a 0 byte to represent the end of the string.

WARNING

It is your responsibility to make sure that the underlying memory is not freed too early. For example, the following code will cause undefined behaviour when `ptr` is used inside the `unsafe` block:

    use std::ffi::{CString};

    let ptr = CString::new("Hello").unwrap().as_ptr();
    unsafe {
        // `ptr` is dangling
        *ptr;
    }Run

This happens because the pointer returned by `as_ptr` does not carry any lifetime information and the string is deallocated immediately after the `CString::new("Hello").unwrap().as_ptr()` expression is evaluated. To fix the problem, bind the string to a local variable:

    use std::ffi::{CString};

    let hello = CString::new("Hello").unwrap();
    let ptr = hello.as_ptr();
    unsafe {
        // `ptr` is valid because `hello` is in scope
        *ptr;
    }Run

#### `fn to_bytes(&self) -> &[u8]`

Converts this C string to a byte slice.

This function will calculate the length of this string (which normally requires a linear amount of work to be done) and then return the resulting slice of `u8` elements.

The returned slice will not contain the trailing nul that this C string has.

> Note: This method is currently implemented as a 0-cost cast, but it is planned to alter its definition in the future to perform the length calculation whenever this method is called.

#### `fn to_bytes_with_nul(&self) -> &[u8]`

Converts this C string to a byte slice containing the trailing 0 byte.

This function is the equivalent of `to_bytes` except that it will retain the trailing nul instead of chopping it off.

> Note: This method is currently implemented as a 0-cost cast, but it is planned to alter its definition in the future to perform the length calculation whenever this method is called.

#### `fn to_str(&self) -> Result<&str, Utf8Error>`
1.4.0

Yields a `&str` slice if the `CStr` contains valid UTF-8.

This function will calculate the length of this string and check for UTF-8 validity, and then return the `&str` if it's valid.

> Note: This method is currently implemented to check for validity after a 0-cost cast, but it is planned to alter its definition in the future to perform the length calculation in addition to the UTF-8 check whenever this method is called.

#### `fn to_string_lossy(&self) -> Cow<str>`
1.4.0

Converts a `CStr` into a `Cow<str>`.

This function will calculate the length of this string (which normally requires a linear amount of work to be done) and then return the resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences with `U+FFFD REPLACEMENT CHARACTER`.

> Note: This method is currently implemented to check for validity after a 0-cost cast, but it is planned to alter its definition in the future to perform the length calculation in addition to the UTF-8 check whenever this method is called.

## Trait Implementations

### `impl PartialEq for CString`
[src]

#### `fn eq(&self, __arg_0: &CString) -> bool`

This method tests for `self` and `other` values to be equal, and is used by `==`. Read more

#### `fn ne(&self, __arg_0: &CString) -> bool`

This method tests for `!=`.

### `impl PartialOrd for CString`
[src]

#### `fn partial_cmp(&self, __arg_0: &CString) -> Option<Ordering>`

This method returns an ordering between `self` and `other` values if one exists. Read more

#### `fn lt(&self, __arg_0: &CString) -> bool`

This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more

#### `fn le(&self, __arg_0: &CString) -> bool`

This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more

#### `fn gt(&self, __arg_0: &CString) -> bool`

This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more

#### `fn ge(&self, __arg_0: &CString) -> bool`

This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. Read more

### `impl Eq for CString`
[src]

### `impl Ord for CString`
[src]

#### `fn cmp(&self, __arg_0: &CString) -> Ordering`

This method returns an `Ordering` between `self` and `other`. Read more

### `impl Hash for CString`
[src]

#### `fn hash<__H: Hasher>(&self, __arg_0: &mut __H)`

Feeds this value into the state given, updating the hasher as necessary.

#### `fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher`
1.3.0

Feeds a slice of this type into the state provided.

### `impl Clone for CString`
[src]

#### `fn clone(&self) -> CString`

Returns a copy of the value. Read more

#### `fn clone_from(&mut self, source: &Self)`

Performs copy-assignment from `source`. Read more

### `impl Drop for CString`
1.13.0
[src]

#### `fn drop(&mut self)`

A method called when the value goes out of scope. Read more

### `impl Deref for CString`
[src]

#### `type Target = CStr`

The resulting type after dereferencing

#### `fn deref(&self) -> &CStr`

The method called to dereference a value

### `impl Debug for CString`
[src]

#### `fn fmt(&self, f: &mut Formatter) -> Result`

Formats the value using the given formatter.

### `impl Default for CString`
1.10.0
[src]

#### `fn default() -> CString`

Creates an empty `CString`.

### `impl Borrow<CStr> for CString`
1.3.0
[src]

#### `fn borrow(&self) -> &CStr`

Immutably borrows from an owned value. Read more

### `impl<'a> From<&'a CStr> for CString`
1.7.0
[src]

#### `fn from(s: &'a CStr) -> CString`

Performs the conversion.

### `impl Index<RangeFull> for CString`
1.7.0
[src]

#### `type Output = CStr`

The returned type after indexing

#### `fn index(&self, _index: RangeFull) -> &CStr`

The method for the indexing (`container[index]`) operation

### `impl AsRef<CStr> for CString`
1.7.0
[src]

#### `fn as_ref(&self) -> &CStr`

Performs the conversion.

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result
+
  Collapse/expand all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)