共享枚举

  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. };
  • 在 Rust 端,为共享枚举生成的代码实际上是封装数值的结构体。这是因为在 C++ 中,枚举类存储与所有已列变体不同的值不属于 UB,而 Rust 表示法需要具有相同的行为。