diff options
| author | Stephane Raux <stephaneyfx@gmail.com> | 2019-07-08 21:34:36 -0700 |
|---|---|---|
| committer | Stephane Raux <stephaneyfx@gmail.com> | 2019-07-09 20:40:16 -0700 |
| commit | 318c5d6c963d0e5d8ece89e804b4e696c6011955 (patch) | |
| tree | 966d9f3394e165178e25c4390deb6c538ae0e9c1 /src/liballoc | |
| parent | 09ab31bc64f4ede9f9498440cb4225c173767c1e (diff) | |
| download | rust-318c5d6c963d0e5d8ece89e804b4e696c6011955.tar.gz rust-318c5d6c963d0e5d8ece89e804b4e696c6011955.zip | |
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](https://github.com/rust-lang/unsafe-code-guidelines/issues/157) in the corresponding repository. It is also related to [the issue](https://github.com/rust-lang/rust/issues/52976) regarding marking `Box<T>` `#[repr(transparent)]`.
Diffstat (limited to 'src/liballoc')
| -rw-r--r-- | src/liballoc/boxed.rs | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 01dee0a3943..50174c3f279 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -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 |
