Skip to content

Mark non-pub fields as private in c++ headers #448

@ejmahler

Description

@ejmahler

If I have the following Rust struct:

#[repr(C)]
pub struct MyStruct {
    value1: i32,
    pub value2: i32
}

It would be very useful for the generated struct to reflect the field's visibility:

struct MyStruct {
private:
    int32_t value1;
public:
    int32_t value2;
};

My main motivation for this is to create exported structs where all fields are private. An example is a pointer wrapper: If I allocate a pointer for an opaque struct with Box and then return the raw pointer, there's nothing stopping the caller from modifying it before passing it back for destruction. If instead I make a struct to wrap it, and give it private fields, all the caller can do is copy the struct around and pass it back unchanged.

A change like this would enable APIs that were more type-safe and more in the spirit of Rust.

An alternate, lower-tech approach would be an annotation to just unconditionally mark all fields private. I imagine most use-cases will want all-private or all-public fields, so an annotation to set them all private might be a smarter solution, and save field-specific visibility for a use case that needs it.

What do you think? Is there interest in this? If so I'd be happy to tackle it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions