Skip to content

Commit

Permalink
Clarify Box<T> representation and its use in FFI
Browse files Browse the repository at this point in the history
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](#52976) regarding marking `Box<T>` `#[repr(transparent)]`.
  • Loading branch information
stephaneyfx committed Jul 10, 2019
1 parent 09ab31b commit 318c5d6
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/liballoc/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,28 @@
//! T` obtained from `Box::<T>::into_raw` may be deallocated using the
//! [`Global`] allocator with `Layout::for_value(&*value)`.
//!
//! `Box<T>` has the same representation as `*mut T`. In particular, when
//! `T: Sized`, this means that `Box<T>` has the same representation as
//! a C pointer, making the following code valid in FFI:
//!
//! ```c
//! /* C header */
//! struct Foo* foo(); /* Returns ownership */
//! void bar(struct Foo*); /* `bar` takes ownership */
//! ```
//!
//! ```
//! #[repr(C)]
//! pub struct Foo;
//!
//! #[no_mangle]
//! pub extern "C" fn foo() -> Box<Foo> {
//! Box::new(Foo)
//! }
//!
//! #[no_mangle]
//! pub extern "C" fn bar(_: Option<Box<Foo>>) {}
//! ```
//!
//! [dereferencing]: ../../std/ops/trait.Deref.html
//! [`Box`]: struct.Box.html
Expand Down

0 comments on commit 318c5d6

Please sign in to comment.