C structs with bit fields and FFI

Well, if anyone is interested in this problem: as it turns out, transforming struct's bit fields into an explicit bit array works perfectly.

Example wrapper function:

uint32_t http_get_struct_flags(const http_parser *state) {
  return state->status_code |
    (state->method << 16) |
    (state->http_errno << 24);
}

And usage in Rust:

fn http_get_struct_flags(parser: *const HttpParser) -> u32;
...
unsafe {
     let flags = http_get_struct_flags(parser_struct as *const _);

     let status_code = (flags & 0xFFFF) as u16;
     let method_code = ((flags >> 16) & 0xFF) as u8;
     let http_errno = ((flags >> 24) & 0x7F) as u8;
     ...
}

But, obviously, the wrapper file should be built using the same compiler (e.g. if you build the lib with GCC, make sure that the wrapper is built with GCC as well).

2 Likes