rust-lang / rust-lang/rust-bindgen

Force generate accessors for fields in C structs

Open
#3,131 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
5.3k
Forks
829
Avg merge
1d 1h
Merged PRs (30d)
15

Description

I encountered a situation where a C API evolved from using a simple struct FooV1 to a bitfield struct FooV2. This change requires different access patterns for the a field, using direct member access (v1.a) versus a getter method (v2.a()).

#pragma once


typedef struct {
    unsigned char a; // a < 32
} FooV1;

// because a < 32, api owners decided to use 5 bits for a and use rest for new fields
typedef struct {
    unsigned char a: 5; // a < 32
    unsigned char b: 3;
} FooV2;
        let v1 = FooV1::default();
        let v2 = FooV2::default();

        let a_v1 = v1.a;
        let a_v2 = v2.a();
        assert_eq!(a_v1, a_v2);

I propose adding a mechanism to force the generation of getter and setter methods for all struct fields, regardless of whether they are bitfields. This would provide consistent access patterns and mitigate breaking changes caused by evolving C APIs using bitfields. For example add bindgen::Builder::force_accessors with regexp support to add structs that need to be generated this way.

If the project uses the library from the system and user uses v1 library it will not be able compile code adopted for v2 library. I want to avoid this because it is not necessarily that such a change is breaking from the point of view of using the C API. (At least, if header and library are the same version)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the bindgen::Builder API and trace how struct fields are currently classified for accessor generation. Define the force_accessors mechanism and its regexp selection behavior, then verify that selected fields consistently receive getter and setter methods regardless of bitfield status.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.