Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rust Enums and Tagged Unions #54

Open
Michael-F-Bryan opened this issue Nov 5, 2017 · 0 comments
Open

Rust Enums and Tagged Unions #54

Michael-F-Bryan opened this issue Nov 5, 2017 · 0 comments

Comments

@Michael-F-Bryan
Copy link
Owner

This problem would pass a normal Rust enum to C++, where the C++ code has declared a tagged union which roughly matches how Rust does things internally.

The solution should mention that this is UB because an enum's internal representation is unspecified. Instead Rust should manually define a tagged union which is the equivalent of our enum, possibly adding the appropriate From<...> impls.

You'd need to explicitly write something like this:

#[derive(Copy, Clone)]
#[repr(C)]
struct Car {
    tag: CarType,
    value: CarValue,
}

#[derive(Copy, Clone)]
#[repr(C)]
union CarValue {
    fast: FastCar,
    slow: SlowCar,
}

#[derive(Copy, Clone, Debug)]
struct FastCar(u32);

#[derive(Copy, Clone, Debug)]
struct SlowCar(f64);

#[derive(Copy, Clone)]
#[repr(C)]
enum CarType {
    Fast,
    Slow,
}

As well as its C equivalent:

struct SlowCar{
  ...
}

struct FastCar{
  ...
}

union union_car {
  FastCar,
  SlowCar
}

enum Cartype{Slow,Fast};

struct Car{
  union_car inner;
  Cartype tag;
} 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant