7

Is it possible to wrap C enums in Rust?

For example C enum example

Maik Klein
  • 15,548
  • 27
  • 101
  • 197

1 Answers1

6

Yes, with no changes (other than whitespace to fit in with prevailing Rust style):

enum List {
    MaxLogLevel = 1,
    MaxNumMessages,
    TrilinearFiltering,
    MaxAnisotropy,
    TexCompression,
    SRGBLinearization,
    LoadTextures,
    FastAnimation,
    ShadowMapSize,
    SampleCount,
    WireframeMode,
    DebugViewMode,
    DumpFailedShaders,
    GatherTimeStats
}

fn main() {
    println!("{} {} {}",
             MaxLogLevel as uint,
             SampleCount as uint,
             GatherTimeStats as uint);
}

Prints 1 10 14.

huon
  • 94,605
  • 21
  • 231
  • 225
  • You made a change! The `{` is on its own line in the original. :P – Chris Morgan Oct 18 '13 at 04:19
  • @ChrisMorgan Fine! We'll have it your way. :P – huon Oct 18 '13 at 04:25
  • There's a second change! The indentation is different! :P – Chris Morgan Oct 18 '13 at 04:42
  • 1
    Thanks but I thought that C optimizes the enums so we never know the real size of the enum, has this changed? – Maik Klein Oct 18 '13 at 08:44
  • 2
    @MaikKlein, not really. [This (currently bitrotted) PR](https://github.com/mozilla/rust/pull/9613) is giving users control over the size of the enums which will make this easier, but, in general, C APIs that use enums are very hard to interface with from other languages (precisely because C compilers are mostly free to choose the size of the enum as they wish). – huon Oct 18 '13 at 10:02
  • 1
    @dbaupp Does this mean that it is impossible to interface with a C lib that uses enums? Or is there a work around? – Maik Klein Oct 18 '13 at 10:08
  • 1
    @MaikKlein, it's hard without forcing the C compiler with which the C lib is built to use a predictable size for enums (e.g. always the smallest possible size, or always `int`). – huon Oct 18 '13 at 10:27
  • If u want to fit size with C u should use `#[repr(C)]`? – S.R Feb 17 '18 at 11:45