diff options
| author | Matthias Geier <Matthias.Geier@gmail.com> | 2024-04-02 18:54:24 +0200 |
|---|---|---|
| committer | Matthias Geier <Matthias.Geier@gmail.com> | 2024-04-02 18:54:24 +0200 |
| commit | 8e91a51cd81de5cf686d21db891634fecdc250c0 (patch) | |
| tree | 6daf5c352f5ed1facbbab107d0bfa39b43e8dbf6 /library/core/src/slice/raw.rs | |
| parent | 5dbaafdb9305df5332157e74eaaa55c615aa489f (diff) | |
| download | rust-8e91a51cd81de5cf686d21db891634fecdc250c0.tar.gz rust-8e91a51cd81de5cf686d21db891634fecdc250c0.zip | |
DOC: Add FFI example for slice::from_raw_parts()
Diffstat (limited to 'library/core/src/slice/raw.rs')
| -rw-r--r-- | library/core/src/slice/raw.rs | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/library/core/src/slice/raw.rs b/library/core/src/slice/raw.rs index 29a12f106c5..d001688d79d 100644 --- a/library/core/src/slice/raw.rs +++ b/library/core/src/slice/raw.rs @@ -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] |
