Skip to content

Commit

Permalink
DOC: Add FFI example for slice::from_raw_parts()
Browse files Browse the repository at this point in the history
  • Loading branch information
mgeier committed Apr 2, 2024
1 parent 9f0af96 commit 08f761f
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions core/src/slice/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,27 @@ use crate::ub_checks;
/// }
/// ```
///
/// ### FFI: Handling null pointers
///
/// In languages such as C++, pointers to empty collections are not guaranteed to be non-null.
/// When accepting such pointers, they have to be checked for null-ness to avoid undefined
/// behavior.
///
/// ```
/// use std::slice;
///
/// unsafe extern "C" fn handle_slice(ptr: *const f32, len: usize) {
/// let data = if ptr.is_null() {
/// // `len` is assumed to be 0.
/// &[]
/// } else {
/// unsafe { slice::from_raw_parts(ptr, len) }
/// };
/// dbg!(data);
/// // ...
/// }
/// ```
///
/// [valid]: ptr#safety
/// [`NonNull::dangling()`]: ptr::NonNull::dangling
#[inline]
Expand Down

0 comments on commit 08f761f

Please sign in to comment.