4 ms·
Is there a good guide on how to make libraries with C bindings in rust? I've been learning it for the past few days but without much of a use case. Fast librari
by HumanDrivenDev 9y ago
Is there a good guide on how to make libraries with C bindings in rust? I've been learning it for the past few days but without much of a use case. Fast libraries with a C API in a higher level language would be very useful though.
- vvanders 9y agoIt's mostly straightforward, you just define with #[no_mangle] + extern fn ... The Rust docs cover it in small detail[1]. FWIW you can do the same with JNI and have direct Java->Rust bindings. If you want to get really clever you can even parse the Rust AST(using syntex) to auto-generate java/headers(there may be libs to do this now, I haven't looked in a while). What's nice about the C FFI is you can pretty much embed Rust anywhere, I've used it in C/C++, Java, C# and Python pretty easily. [1] https://doc.rust-lang.org/book/second-edition/ch19-01-unsafe-rust.html#calling-rust-functions-from-other-languages https://doc.rust-lang.org/book/second-edition/ch19-01-unsafe...
- Manishearth 9y agoThere's a tool called cbindgen (https://github.com/eqrion/cbindgen https://github.com/eqrion/cbindgen) that generates header files from rust code . It's a bit experimental. The reverse tool, bindgen (https://github.com/rust-lang-nursery/rust-bindgen/ https://github.com/rust-lang-nursery/rust-bindgen/) is more mature -- generates rust bindings from header files.
- vvanders 9y agoOh yeah, I should have mentioned bindgen, it's fantastic!
- samjs 9y agoI wrote on a similar topic [1], about writing system libraries in Rust with a C API and bindings to other languages. Which covers a bit of this, plus some of the sharp edges of FFI. Most of the trickier parts of it are covered in the FFI omnibus [2]. Also worth checking out is the cbindgen tool [3]. [1]: https://libpasta.github.io/blog/bindings/ https://libpasta.github.io/blog/bindings/ [2]: http://jakegoulding.com/rust-ffi-omnibus/ http://jakegoulding.com/rust-ffi-omnibus/ [3]: https://github.com/eqrion/cbindgen https://github.com/eqrion/cbindgen