Skip to content

Commit 318c5d6

Browse files
committed
Clarify Box<T> representation and its use in FFI
This officializes what was only shown as a code example in [the unsafe code guidelines](https://rust-lang.github.io/unsafe-code-guidelines/layout/function-pointers.html?highlight=box#use) and follows [the discussion](rust-lang/unsafe-code-guidelines#157) in the corresponding repository. It is also related to [the issue](rust-lang#52976) regarding marking `Box<T>` `#[repr(transparent)]`.
1 parent 09ab31b commit 318c5d6

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/liballoc/boxed.rs

+22
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,28 @@
6363
//! T` obtained from `Box::<T>::into_raw` may be deallocated using the
6464
//! [`Global`] allocator with `Layout::for_value(&*value)`.
6565
//!
66+
//! `Box<T>` has the same representation as `*mut T`. In particular, when
67+
//! `T: Sized`, this means that `Box<T>` has the same representation as
68+
//! a C pointer, making the following code valid in FFI:
69+
//!
70+
//! ```c
71+
//! /* C header */
72+
//! struct Foo* foo(); /* Returns ownership */
73+
//! void bar(struct Foo*); /* `bar` takes ownership */
74+
//! ```
75+
//!
76+
//! ```
77+
//! #[repr(C)]
78+
//! pub struct Foo;
79+
//!
80+
//! #[no_mangle]
81+
//! pub extern "C" fn foo() -> Box<Foo> {
82+
//! Box::new(Foo)
83+
//! }
84+
//!
85+
//! #[no_mangle]
86+
//! pub extern "C" fn bar(_: Option<Box<Foo>>) {}
87+
//! ```
6688
//!
6789
//! [dereferencing]: ../../std/ops/trait.Deref.html
6890
//! [`Box`]: struct.Box.html

0 commit comments

Comments
 (0)