rust-bindgen icon indicating copy to clipboard operation
rust-bindgen copied to clipboard

Force generate accessors for fields in C structs

Open SpeedCrash100 opened this issue 10 months ago • 0 comments

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)

SpeedCrash100 avatar Feb 15 '25 05:02 SpeedCrash100