Shared Enums

  1. #[cxx::bridge]
  2. mod ffi {
  3. enum Suit {
  4. Clubs,
  5. Diamonds,
  6. Hearts,
  7. Spades,
  8. }
  9. }

Generated Rust:

  1. #![allow(unused)]
  2. fn main() {
  3. #[derive(Copy, Clone, PartialEq, Eq)]
  4. #[repr(transparent)]
  5. pub struct Suit {
  6.     pub repr: u8,
  7. }
  8. #[allow(non_upper_case_globals)]
  9. impl Suit {
  10.     pub const Clubs: Self = Suit { repr: 0 };
  11.     pub const Diamonds: Self = Suit { repr: 1 };
  12.     pub const Hearts: Self = Suit { repr: 2 };
  13.     pub const Spades: Self = Suit { repr: 3 };
  14. }
  15. }

Generated C++:

  1. enum class Suit : uint8_t {
  2. Clubs = 0,
  3. Diamonds = 1,
  4. Hearts = 2,
  5. Spades = 3,
  6. };
  • On the Rust side, the code generated for shared enums is actually a struct wrapping a numeric value. This is because it is not UB in C++ for an enum class to hold a value different from all of the listed variants, and our Rust representation needs to have the same behavior.