FFI
I have a question regarding FFI. I've used FFI in Python, Java (JNA and JNI) and LuaJIT, and LuaJIT's mechanism is just so much better than anything else (despite Lua being the language I have used the least before). I've created a gist here showing how to use the XInput library via LuaJIT's FFI.
In LuaJIT, you can just include the C header part, which very often works verbatim and even handles pack pragmas/atributes for structs correctly.
Why did Rust choose to handle FFI the way it does instead of allowing a similar import mechanism, given that it already includes the necessary LLVM tooling?
Posted Aug 28, 2015, 7:09 PM UTC
LLVM doesn't include code for parsing C. What Rust uses is the LLVM backend that understands the various C calling conventions, while what you need for parsing C this way would be something like the Clang frontend.
As a matter of fact, there is the rust-bindgen project which does use the Clang frontend to parse C and generate Rust bindings.
For the most part, I think that the reason this is done the way it is is to keep the Rust compiler smaller and simpler. You don't need to provide a full C frontend as well; Rust just provides enough that you can manually write bindings, which is fine for simple APIs. For very large APIs, you can use third-party projects like rust-bindgen, without it having to be tied to the development cycle of the compiler, and without it complicating the basic language semantics and maintenance of the compiler.