- Start Date: 2014-05-17
- RFC PR: rust-lang/rfcs#79
- Rust Issue: rust-lang/rust#14309
Summary
Leave structs#[repr(C)]
to expose C compatible layout.
Motivation
The members of a struct
will put the u8
first in memory, then the u64
, the i8
and lastly the i64
. Due to the alignment1 + 8 + 1 + 8 == 18
bytes, but rather 1 + 7 + 8 + 1 + 7 + 8 == 32
bytes, since it is laid out like
If the fields were reordered to
then the structu64
forces it to take
Having an undefined layout does allowunsafe
code).
Notably, Rust's enum
s already have undefined layout, and provide the #[repr]
attribute to control
Drawbacks
Forgetting to add #[repr(C)]
for a structenum
s without a #[repr(...)]
attribute, so this can be extended
Having an unspecifiedrepr(C)
attribute. This situation seems relatively similarHash
if one wishes to use it as a hashmap key.
It is slightly better if structs
That said, this scenario requires:
- Needing to pass a Rust struct構造、構造体into C/FFI code, where that FFI code actually needs to use things from the struct,構造、構造体rather than just pass it through, e.g., back into a Rust callback.
- The Rust struct構造、構造体is defined定義するupstream & out of your control,制御するand not intended for use with C code.
- The C/FFI code is designed設計(する)by someone other than that vendor, or otherwiseさもなければnot designed設計(する)for use with the Rust struct構造、構造体(or else it is a bug in the vendor's library that the Rust struct構造、構造体can't be sanely passed to C).
Detailed design設計(する)
A struct
has no fixed layout, that is, a compiler can choose whichever order
A fixed layout can be selected with the #[repr]
attribute
This will force a struct
There would be a lint for the use of non-repr(C)
structs
Alternatives代わりのもの、選択肢
- Have non-C layouts opt-in, via
#[repr(smallest)]
and#[repr(random)]
(or similar). - Have layout defined,定義するbut not declaration宣言order順序(like Java(?)), for example, from largest field to smallest, so
u8
fields get placed last, and[u8, .. 1000000]
fields get placed first. The#[repr]
attributes would still allow許可する、可能にするfor selecting declaration-order layout.
Unresolved questions
- How does this interact with binary2進数compatibility互換性of dynamic動的libraries?
- How does this interact with DST, where some fields have to be at the end of a struct? (Just always lay-out unsized fields last? (i.e. after monomorphisation if a field was originally marked
Sized?
then it needs to be last).)