Skip to content

Document the correct FFI equivalent to a C opaque struct #27303

Closed
@crumblingstatue

Description

@crumblingstatue

With recent changes to the improper_ctypes lint, it now rejects #[repr(C)] struct Foo; for representing a C opaque struct.

#[repr(C)]
pub struct Foo;

extern "C" {
    pub fn foo(arg: *const Foo);
}

fn main() {
}
foo.rs:5:25: 5:28 warning: found zero-size struct in foreign module, consider adding a member to this struct, #[warn(improper_ctypes)] on by default
foo.rs:5    pub fn foo(arg: *const Foo);
                                   ^~~

On the #rust IRC channel, I have asked what is the proper way to represent a C opaque struct, but no definitive answer was reached.

Some of the answers were:

  • struct Foo; is incorrect.
  • struct Foo; is fine, but it can break certain LLVM optimizations.
  • Use c_void instead. This isn't satisfactory when it is desirable to represent a C opaque struct as a distinct type in your API.
  • Use a newtype wrapper around c_void. Someone said this might not be correct either.
  • Rustc should allow #repr(C) enum Foo {}. It doesn't currently allow this.

This should be properly researched and then documented in the official documentation, so users know what to use for representing C opaque struct types in Rust when interfacing with C code.

Some relevant issues:

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