共享枚举

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. }

9. #[allow(non_upper_case_globals)]
10. impl Suit {
11. pub const Clubs: Self = Suit { repr: 0 };
12. pub const Diamonds: Self = Suit { repr: 1 };
13. pub const Hearts: Self = Suit { repr: 2 };
14. pub const Spades: Self = Suit { repr: 3 };
15. }
16. }

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 表示法需要具有相同的行为。