pub fn construct_libc_cstring(string: &str) -> *mut libc::c_char {
    let char_size = 1; // 1 byte
    let c_string: *mut libc::c_char;
    unsafe {
        c_string = std::mem::transmute(
            // + 1: null terminated
            libc::malloc( char_size * (string.len() + 1))
        );
    }

    let chars = string.chars().collect::<Vec<char>>();
    for i in 0..chars.len() {
        unsafe {
            *c_string.offset(i as isize) = chars[i] as libc::c_char;
        }
    }

    // null terminated
    unsafe {
        *c_string.offset(string.len() as isize) = 0;
    }

    c_string
}
/// Allocates memory on the heap and constructs a null-terminated C string
/// from a Rust string.
/// I've chosen to use `*mut libc::c_char"` rather than `std::ffi::CStr`
/// because of educational purposes, to gain more experience, and just
/// for fun.
Allocates memory on the heap and constructs a null-terminated C string
from a Rust string.
Allocates memory on the heap and constructs a null - terminated C string from a Rust string .
pub fn construct_libc_cstring(string: &str) -> *mut libc::c_char {
    let char_size = 1; // 1 byte
    let c_string: *mut libc::c_char;
    unsafe {
        c_string = std::mem::transmute(
            // + 1: null terminated
            libc::malloc( char_size * (string.len() + 1))
        );
    }
    let chars = string.chars().collect::<Vec<char>>();
    for i in 0..chars.len() {
        unsafe {
            *c_string.offset(i as isize) = chars[i] as libc::c_char;
        }
    }
    // null terminated
    unsafe {
        *c_string.offset(string.len() as isize) = 0;
    }
    c_string
}
pub fn construct_libc_cstring ( string : & str ) -> * mut libc :: c_char { let char_size = 1 ; // 1 byte let c_string : * mut libc :: c_char ; unsafe { c_string = std :: mem :: transmute ( // + 1: null terminated libc :: malloc ( char_size * ( string . len ( ) + 1 ) ) ) ; } let chars = string . chars ( ) . collect :: < Vec < char > > ( ) ; for i in 0 .. chars . len ( ) { unsafe { * c_string . offset ( i as isize ) = chars [ i ] as libc :: c_char ; } } // null terminated unsafe { * c_string . offset ( string . len ( ) as isize ) = 0 ; } c_string }
Allocates memory on the heap and constructs a null-terminated C string
from a Rust string.
Allocates memory on the heap and constructs a null - terminated C string from a Rust string .
string
&str
string
&str