Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 08f761f

Browse files
committedApr 2, 2024
DOC: Add FFI example for slice::from_raw_parts()
1 parent 9f0af96 commit 08f761f

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
 

‎core/src/slice/raw.rs

+21
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,27 @@ use crate::ub_checks;
8383
/// }
8484
/// ```
8585
///
86+
/// ### FFI: Handling null pointers
87+
///
88+
/// In languages such as C++, pointers to empty collections are not guaranteed to be non-null.
89+
/// When accepting such pointers, they have to be checked for null-ness to avoid undefined
90+
/// behavior.
91+
///
92+
/// ```
93+
/// use std::slice;
94+
///
95+
/// unsafe extern "C" fn handle_slice(ptr: *const f32, len: usize) {
96+
/// let data = if ptr.is_null() {
97+
/// // `len` is assumed to be 0.
98+
/// &[]
99+
/// } else {
100+
/// unsafe { slice::from_raw_parts(ptr, len) }
101+
/// };
102+
/// dbg!(data);
103+
/// // ...
104+
/// }
105+
/// ```
106+
///
86107
/// [valid]: ptr#safety
87108
/// [`NonNull::dangling()`]: ptr::NonNull::dangling
88109
#[inline]

0 commit comments

Comments
 (0)
Failed to load comments.