Skip to content

Commit a425a42

Browse files
committed
Add methods for handing CStrings back and forth to C
1 parent 2ebc3e3 commit a425a42

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

Diff for: src/libstd/ffi/c_str.rs

+29-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
#![unstable(feature = "std_misc")]
1212

1313
use borrow::{Cow, ToOwned};
14-
use boxed::Box;
14+
use boxed::{self, Box};
1515
use clone::Clone;
1616
use convert::{Into, From};
1717
use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
@@ -202,6 +202,34 @@ impl CString {
202202
CString { inner: v.into_boxed_slice() }
203203
}
204204

205+
/// Retakes ownership of a CString that was transferred to C.
206+
///
207+
/// The only appropriate argument is a pointer obtained by calling
208+
/// `into_ptr`.
209+
#[unstable(feature = "c_str_memory", reason = "recently added")]
210+
pub unsafe fn from_ptr(ptr: *const libc::c_char) -> CString {
211+
let len = libc::strlen(ptr);
212+
let len_with_nul = len as usize + 1;
213+
let vec = Vec::from_raw_parts(ptr as *mut u8, len_with_nul, len_with_nul);
214+
CString { inner: vec.into_boxed_slice() }
215+
}
216+
217+
/// Transfers ownership of the string to a C caller.
218+
///
219+
/// The pointer must be returned to Rust and reconstituted using
220+
/// `from_ptr` to be properly deallocated. Specifically, one
221+
/// should *not* use the standard C `free` function to deallocate
222+
/// this string.
223+
///
224+
/// Failure to call `from_ptr` will lead to a memory leak.
225+
#[unstable(feature = "c_str_memory", reason = "recently added")]
226+
pub fn into_ptr(self) -> *const libc::c_char {
227+
// It is important that the bytes be sized to fit - we need
228+
// the capacity to be determinable from the string length, and
229+
// shrinking to fit is the only way to be sure.
230+
boxed::into_raw(self.inner) as *const libc::c_char
231+
}
232+
205233
/// Returns the contents of this `CString` as a slice of bytes.
206234
///
207235
/// The returned slice does **not** contain the trailing nul separator and

0 commit comments

Comments
 (0)