by bpolverini · 3y ago · 0 comments
The benefits of Rust's (wonderful) model around references and lifetimes come at a significant cost to ergonomics when having to go into the Mordor of some C library and back. I usually find myself wishing I could have some macro where I just write in C and have it exposed as an unsafe back in Rust. I know I can do this by just writing a C dylib and integrating that, but now I've got two problems.
Even still, I prefer writing unsafe Rust to writing C. std::mem::ptr forces me to ask the right questions and reminds me of just how easy it is to fall into UB in C as well.
In D you can just import a .c file mycfile.c with:
import mycfile; // C file filled with C functions
and they'll be treated as @system code by the D semantics. They're even inlinable.I'm not sure it's what you're looking for, but it seems like a good starting point.
As for the general thrust of your comment and the article, I agree. It'll be interesting to see what changes come to make things nicer.
This transpiles C to Rust at compile time, though it requires a nightly compiler and hasn't been updated in some time. But it's exactly what you're looking for. C code in, unsafe Rust code out.
This freaks me out the most in networking code, where there is all kinds of casting of structs (esp. if you blindly copy-paste examples from StackOverflow) and performance usually matters. Rust has inspired me to take more time to profile C code to see whether strict aliasing (strict overflow, etc.) actually make a significant enough improvement to merit the UB-risk, review time, and acid in the stomach.
There’s a macro for doing this with Assembly, I can imagine one could be made for C. But why wouldn’t you just write unsafe rust at that point?