Description
#43036 added #[repr(transparent)]
with one of the goals being safe FFI interaction for newtypes, and added that attribute to bunch of built-in types such as NonZero
, Waker
, Unique
etc.
One use-case that could be really helpful for FFI though is adding it to Box<T>
. I haven't found any previous discussions on pros and cons of doing so, so apologies if this is way off and there are obvious reasons why it can't be such, but as far as I can tell, this is not a breaking change neither from API nor from memory representation perspective.
Looking from definition, Box
is just a wrapper around Unique
which is already #[repr(transparent)]
and wraps NonNull
which is also #[repr(transparent)]
which, in turn, wraps raw pointer which is FFI-safe.
Adding this attribute to Box
would make it transparent wrapper all the way down around a raw pointer, and so would allow to do FFI interactions by simply leaking Box
as return type in allocator functions and accepting it as-is in deallocator function without manual into_raw
and from_raw
conversions.
Aside from ergonomics improvement (allocation / deallocation is pretty common operation in cdylib
s), this would also allow code to be more self-documenting as just from looking at rustdoc you would be able to tell which pointers are owned and will be allocated or consumed by Rust side.
Counter-argument might be that one can implement custom transparent CBox
on top of NonNull
, but this involves reimplementing many APIs and guarantees Box
already provides e.g. Unique
is not exposed at the moment, and then you also have various standard traits that "just work" with Box
, so if it would be possible to avoid reimplementing all of that with no obvious downsides, it might be still useful to shared library authors.