简体   繁体   中英

Why does rust libc use repr(packed) for struct?

Rust libc use repr(packed) as shown here for struct which will be then passed to system libc. For example, utsname is repr(packed) and then used in fn uname As per the doc mentioned here ,

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),

Then why does rust libc use repr(packed) and not repr(C) for passing struct to system libc?

Then why does rust libc use repr(packed) and not repr(C) for passing struct to system libc?

One obvious reason is that the equivalent structures are specified as packed on the C side as well. (Many C compilers support "packed" as a non-standard extension with the same meaning as in Rust.) The definition of epoll_event on Linux confirms this:

#ifdef __x86_64__
#define EPOLL_PACKED __attribute__((packed))
#else
#define EPOLL_PACKED
#endif

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

The same should apply to the other examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM