|
63 | 63 | //! T` obtained from `Box::<T>::into_raw` may be deallocated using the
|
64 | 64 | //! [`Global`] allocator with `Layout::for_value(&*value)`.
|
65 | 65 | //!
|
66 |
| -//! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented as a |
67 |
| -//! single pointer and is also ABI-compatible with C pointers (i.e. the C type |
68 |
| -//! `T*`). This means that you can have Rust code which passes ownership of a |
69 |
| -//! `Box<T>` to C code by using `Box<T>` as the type on the Rust side, and |
70 |
| -//! `T*` as the corresponding type on the C side. As an example, consider this |
71 |
| -//! C header which declares functions that create and destroy some kind of |
72 |
| -//! `Foo` value: |
| 66 | +//! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented |
| 67 | +//! as a single pointer and is also ABI-compatible with C pointers |
| 68 | +//! (i.e. the C type `T*`). This means that if you have extern "C" |
| 69 | +//! Rust functions that will be called from C, you can define those |
| 70 | +//! Rust functions using `Box<T>` types, and use `T*` as corresponding |
| 71 | +//! type on the C side. As an example, consider this C header which |
| 72 | +//! declares functions that create and destroy some kind of `Foo` |
| 73 | +//! value: |
73 | 74 | //!
|
74 | 75 | //! ```c
|
75 | 76 | //! /* C header */
|
|
108 | 109 | //! is to only use `Box<T>` for pointers that originated from the global
|
109 | 110 | //! allocator.
|
110 | 111 | //!
|
| 112 | +//! **Important.** At least at present, you should avoid using |
| 113 | +//! `Box<T>` types for functions that are defined in C but invoked |
| 114 | +//! from Rust. In those cases, you should directly mirror the C types |
| 115 | +//! as closely as possible. Using types like `Box<T>` where the C |
| 116 | +//! definition is just using `T*` can lead to undefined behavior, as |
| 117 | +//! described in [rust-lang/unsafe-code-guidelines#198][ucg#198]. |
| 118 | +//! |
| 119 | +//! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198 |
111 | 120 | //! [dereferencing]: ../../std/ops/trait.Deref.html
|
112 | 121 | //! [`Box`]: struct.Box.html
|
113 | 122 | //! [`Global`]: ../alloc/struct.Global.html
|
|
0 commit comments