In this article, we will explore how to integrate Rust with other languages such as C, WebAssembly, and others, using techniques like FFI (Foreign Function Interface) among others.
Rust can be a complement to other languages in your project due to its safety, concurrency, and performance characteristics. Also, it can be effectively intermingled with legacy systems written in other languages.
Rust can be called from C (and C++) as well as call C from Rust. This is mainly possible because Rust uses the ABI of the C language. It's relatively simple to link C and Rust code together at runtime.
Here's how C can call Rust:
// This is the Rust function we'd like to call from C
#[no_mangle]
pub extern "C" fn my_rust_function() -> i32 {
42
}
And here's how Rust can call C:
// Declare an extern block with the C functions
extern "C" {
fn my_c_function(arg: i32);
}
fn main() {
unsafe { my_c_function(42); }
}
WebAssembly or wasm is a binary instruction format for a stack-based virtual machine.
Rust supports WebAssembly as a first-class citizen. Here is a step by step guide:
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
$ rustup target add wasm32-unknown-unknown
$ cargo new --lib hello_world
$ cd hello_world && cargo build --target=wasm32-unknown-unknown
Rust can be integrated with other languages beyond C and WebAssembly. Though the process may vary depending on the specific language, the general idea remains the same. The function to be called is declared external in the calling code, and the called function is declared with #[no_mangle] and the extern keyword in the called code.
Rust can be integrated with many other languages, offering an effective way to leverage its strengths in a multilingual environment. While there are pitfalls, understanding how to navigate them can offer substantial benefits in safety, concurrency, and performance.
That's it! You should now know how to call Rust from other languages and call other languages from Rust.