为什么 Rust 的 libc 在结构体中使用 repr(packed)?

3
Rust libc使用repr(packed),如此处所示,用于结构体,并将其传递给系统libc。例如,utsname使用repr(packed),然后在fn uname中使用。 根据此处提到的文档。
repr(packed) forces Rust to strip any padding, and only align the type to a byte. This may improve the memory footprint, but will likely have other negative side-effects.

In particular, most architectures strongly prefer values to be aligned. This may mean the unaligned loads are penalized (x86),

那么,为什么 Rust libc 在将结构体传递给系统 libc 时使用 repr(packed) 而不是 repr(C)
1个回答

3
为什么Rust libc使用repr(packed)而不是repr(C)来传递结构体给系统libc呢?
一个明显的原因是等效的结构在C端也被指定为packed。(许多C编译器支持"packed"作为非标准扩展,具有与Rust中相同的含义。) Linux上的epoll_event定义证实了这一点:
#ifdef __x86_64__
#define EPOLL_PACKED __attribute__((packed))
#else
#define EPOLL_PACKED
#endif

struct epoll_event {
        __u32 events;
        __u64 data;
} EPOLL_PACKED;

同样的规则也应该适用于其他示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接