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

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

Representation of a borrowed C string.

This dynamically sized type is only safely constructed via a borrowed version of an instance of CString. This type can be constructed from a raw C string as well and represents a C string borrowed from another location.

Note that this structure is not repr(C) and is not recommended to be placed in the signatures of FFI functions. Instead safe wrappers of FFI functions may leverage the unsafe from_ptr constructor to provide a safe interface to other consumers.

Examples

Inspecting a foreign C string

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

extern { fn my_string() -> *const c_char; }

fn main() {
    unsafe {
        let slice = CStr::from_ptr(my_string());
        println!("string length: {}", slice.to_bytes().len());
    }
}

Passing a Rust-originating C string

use std::ffi::{CString, CStr};
use std::os::raw::c_char;

fn work(data: &CStr) {
    extern { fn work_with(data: *const c_char); }

    unsafe { work_with(data.as_ptr()) }
}

fn main() {
    let s = CString::new("data data data data").unwrap();
    work(&s);
}

Converting a foreign C string into a Rust String

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

extern { fn my_string() -> *const c_char; }

fn my_string_safe() -> String {
    unsafe {
        CStr::from_ptr(my_string()).to_string_lossy().into_owned()
    }
}

fn main() {
    println!("string: {}", my_string_safe());
}