How does a C-style struct with a bitfield get represented in a Rust #[repr(C)] struct?

后端 未结 1 1281
深忆病人
深忆病人 2020-12-07 03:02

I have a C struct defined as:

struct my_c_s {
    u_char          *ptr;
    unsigned        flag_a:1;
    unsigned              


        
相关标签:
1条回答
  • 2020-12-07 03:15

    No, you can't.

    There is an open issue about supporting bitfields, which doesn't seem to be active. In the issue, @retep998 explains how bitfields are handled in winapi. That might be helpful if you need to handle bitfields in C interface.

    OP seems to aim at C interoperation, but if you just need bitfields functionality, there are several solutions.

    • You should always consider simple redundant solution: avoid bitfields and let fields align naturally.
    • bitfield, according to the comment -- I didn't know that, but it seems to provide C bitfields equivalent.
    • bitflags. This seems suitable for bit-based flags, which typically represented as enum in C.
    • #[repr(packed)] if you just want to pack fields to some degree, ignoring alignment. The fields will still be aligned to byte boundary.
    • bit-vec if you need homogenious arrays of bits.
    0 讨论(0)
提交回复
热议问题