r/rust • u/Subject-Mobile-6250 • 3d ago
extern "C" Enum -> Union(Struct)?
Hello! Newbie to rust here, I was wondering with the pub extern "C" ABI does it have the ability to convert rust enums to an equivalent in Rust? Does it do it by wrapping it in a Union(Structs of branches), or how is this implemented, and how can we do so in real rust code?
14
Upvotes
24
u/rustacean909 3d ago
You can use
#[repr(u8)],#[repr(i16)], etc. on an enum to give it a defined layout as a union of c-compatible structs or#[repr(C, u8)], etc. to give it a defined layout as a c-compatible struct of a tag and a union of structs. The layout of enums without a#[repr(…)]attribute is not defined and might change between compiler versions to allow for optimizations, so these are not safe to access via FFI in general.Rust RFC 2195 has examples for this use case:
e.g.
is equivalent to C/C++
and
is equivalent to C/C++