How is a C-style structure with a bitfield represented in a Rust # [repr (C)] structure?
I have a C structure defined as:
struct my_c_s {
u_char *ptr;
unsigned flag_a:1;
unsigned flag_b:1;
int some_num;
}
How would flag_a
u be presented flag_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,
}
Can I declare them as Or should it all be some kind of set of bits with one field and then I cross them out?bool
s?
eg. pub flag_bits: ::libc::c_uint,
source to share
No, you cannot.
There is an open issue regarding bit-field support that doesn't seem to be active. In this issue @ retep998 explains how bit fields are handled inwinapi
. This can be useful if you need to handle bit fields in the C interface.
The OP seems to be targeting C interoperability, but if you just want the bitpod functionality, there are several solutions.
- You should always consider a simple redundant solution: avoid bit-fields and let the fields align naturally.
-
bitfield
, as per the comment - I didn 't know this, but it seems to be the bit equivalent of C. -
bitflags
... This seems appropriate for bit flags, which are commonly referred to asenum
in C. -
#[repr(packed)]
if you just want to pack the margins to some extent, ignoring the alignment. The margins will still be byte-aligned. -
bit-vec
if you want homogeneous bit arrays.
source to share