How to translate abstract data types from C to Rust?

This recommendation, which I've followed for a long time, says to use an empty enum, but recently, after looking at the unsafe_unwrap crate, I've become paranoid that Rust will make some weird optimizations around that. Is this practice well-defined, and if not, what should be done instead?

https://github.com/rust-lang-nursery/nomicon/issues/29

1 Like

Well, this is worrying. Doesn't this mean tons of libraries are relying on undefined behavior?

*mut Void is well defined. &Void is not.

3 Likes

Whether any existing code is susceptible to UB depends on how they're using it; if it's merely as "typed" raw pointers, then it should be OK. If they, however, also use it in other ways (e.g. forming Rust references to them and then matching on it, storing them as fields, etc) then they probably have broken code today.

If you're using nightly, you can experiment with #![feature(extern_types)]:

https://github.com/rust-lang/rust/issues/43467