#![allow(non_camel_case_types)]
use libc::{c_uchar, size_t};
use std::str::FromStr;
use std::ffi::{CString, NulError};
use std::slice;
#[repr(C)]
pub struct c_str_t {
pub len: size_t,
pub data: *const c_uchar,
}
pub trait MyCStrExt<T> {
fn to_c_str(&self) -> Result<c_str_t, NulError>;
}
pub trait MyCStringExt {
fn from_c_str_ref(nstr: &c_str_t) -> Option<String>;
}
impl<'a> MyCStrExt<&'a str> for str {
fn to_c_str(&self) -> Result<c_str_t, NulError> {
let result = match CString::new(&self[..]) {
Ok(result) => result,
Err(e) => {
return Err(e);
}
};
Ok(c_str_t { data: result.as_ptr() as *const u8, len: self.len() })
}
}
impl MyCStringExt for String {
fn from_c_str_ref(nstr: &c_str_t) -> Option<String> {
unsafe {
if nstr.data.is_null() {
return None;
}
let value = slice::from_raw_parts(nstr.data, nstr.len);
match String::from_utf8(value.to_vec()) {
Ok(value) => Some(value),
Err(e) => None
}
}
}
}
With this test that first converts to a CString
and then back again to a Rust string, passing in the given string
#[test]
fn test_to_c_str() {
let s = "What does the fox say?";
let result = s.to_c_str();
let round_trip = String::from_c_str_ref(result.as_ref().ok().unwrap());
println!("{:?}", round_trip);
}
will result in a round trip with a Rust string at the end with a null in the first character position:
Some("\u{0}hat does the fox say?")
What am I doing wrong?
as_ptr
? – trentcl Jan 12 '18 at 23:45