Skip to content

Commit e20a6db

Browse files
committed
Add methods for handing CStrings back and forth to C
1 parent 97294be commit e20a6db

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

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`. The length of the string will be recalculated
209+
/// using the pointer.
210+
#[unstable(feature = "cstr_memory", reason = "recently added")]
211+
pub unsafe fn from_ptr(ptr: *const libc::c_char) -> CString {
212+
let len = libc::strlen(ptr) + 1; // Including the NUL byte
213+
let slice = slice::from_raw_parts(ptr, len as usize);
214+
CString { inner: mem::transmute(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 = "cstr_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)