带有位域的 C 风格结构如何在 Rust #[repr(C)] 结构中表示? [英] How does a C-style struct with a bitfield get represented in a Rust #[repr(C)] struct?

查看:457
本文介绍了带有位域的 C 风格结构如何在 Rust #[repr(C)] 结构中表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C 结构定义为:

I have a C struct defined as:

struct my_c_s {
    u_char          *ptr;
    unsigned        flag_a:1;
    unsigned        flag_b:1;
    int             some_num;
}

flag_aflag_b 将如何表示?

#[repr(C)]
pub struct my_rust_s {
    pub ptr: *const u_char,
    //pub flag_a: ?,
    //pub flag_b: ?,
    pub some_num: ::libc::c_int,
}

我可以将它们声明为 bools 吗? 或者整个事情是否需要某种具有单个字段的位集,然后我将它们位屏蔽掉?

Can I declare them as bools? Or does that whole thing need to be some sort of set of bits with a single field, and then I bitmask them out?

例如pub flag_bits: ::libc::c_uint,

推荐答案

不,你不能.

有关于支持位域的一个悬而未决的问题,这似乎没有要活跃.在问题中,@retep998 解释了如何在 winapi<中处理位域/代码>.如果您需要在 C 接口中处理位域,这可能会有所帮助.

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 似乎针对 C 互操作,但如果您只需要位域功能,有几种解决方案.

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

  • 您应该始终考虑简单的冗余解决方案:避免位字段并让字段自然对齐.
  • bitfield,根据 评论 -- 我不知道那个,但它似乎提供了等效的 C 位域.
  • bitflags.这似乎适用于基于位的标志,在 C 中通常表示为 enum.
  • #[repr(packed)] 如果您只想在某种程度上打包字段,而忽略对齐.字段仍将与字节边界对齐.
  • bit-vec 如果您需要同构的位数组.
  • 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.

这篇关于带有位域的 C 风格结构如何在 Rust #[repr(C)] 结构中表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆