From ff86ab64b732e79bda62b965b8e2b10786ecc000 Mon Sep 17 00:00:00 2001 From: Jake Goulding Date: Mon, 25 May 2015 12:37:45 -0400 Subject: [PATCH] Add methods for handing allocated strings back to C --- src/libstd/ffi/c_str.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 8c066b3dc2e81..024149f0cc44f 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -200,6 +200,28 @@ impl CString { CString { inner: v } } + /// Retakes ownership from a Rust string that has been returned to C. + pub unsafe fn from_raw_ptr(ptr: *const libc::c_char) -> CString { + let len = libc::strlen(ptr); + let len_with_nul = len as usize + 1; + let vec = Vec::from_raw_parts(ptr as *mut u8, len_with_nul, len_with_nul); + CString::from_vec_unchecked(vec) + } + + /// Transfers ownership from Rust to C. Be warned that the string + /// must be returned to Rust and reconstituted via `from_raw_ptr` + /// to be properly deallocated. + pub fn into_raw_ptr(self) -> *const libc::c_char { + // Resize the vector to fit - we need the capacity to be + // determinable from the string length, and shrinking to fit + // is the only way to be sure. + let mut vec = self.inner; + vec.shrink_to_fit(); + let ptr = vec.as_ptr() as *const libc::c_char; + mem::forget(vec); + ptr + } + /// Returns the contents of this `CString` as a slice of bytes. /// /// The returned slice does **not** contain the trailing nul separator and