Skip to content

Commit 93abc2f

Browse files
committed
Add doc example for CString::from_raw.
1 parent d3c26fe commit 93abc2f

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/libstd/ffi/c_str.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,27 @@ impl CString {
287287
/// to undefined behavior or allocator corruption.
288288
///
289289
/// [`into_raw`]: #method.into_raw
290+
///
291+
/// # Examples
292+
///
293+
/// Create a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
294+
/// ownership with `from_raw`:
295+
///
296+
/// ```no_run
297+
/// use std::ffi::CString;
298+
/// use std::os::raw::c_char;
299+
///
300+
/// extern {
301+
/// fn some_extern_function(s: *mut c_char);
302+
/// }
303+
///
304+
/// let c_string = CString::new("Hello!").unwrap();
305+
/// let raw = c_string.into_raw();
306+
/// unsafe {
307+
/// some_extern_function(raw);
308+
/// let c_string = CString::from_raw(raw);
309+
/// }
310+
/// ```
290311
#[stable(feature = "cstr_memory", since = "1.4.0")]
291312
pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
292313
let len = libc::strlen(ptr) + 1; // Including the NUL byte

0 commit comments

Comments
 (0)