Let's say I have one program written in Rust and another in C++. Given that they both are compiled to Wasm, can I somehow call a function in one program from the other?
If you have some Rust code, you can compile it into WebAssembly (wasm). This tutorial takes you through all you need to know to compile a Rust project to wasm and use it in an existing web app.
WebAssembly is a compilation target for C, C++, Go, and Rust among others. Developers can code in any of those languages and then compile their source into Wasm binaries. These then run alongside JS code in their apps. There are many obvious reasons why WebAssembly is faster than JavaScript.
wasm-pack is a tool for assembling and packaging Rust crates that target WebAssembly. These packages can be published to the npm Registry and used alongside other packages. This means you can use them side-by-side with JS and other packages, and in many kind of applications, be it a Node.
To call Rust from JavaScript, you need to compile the Rust code to Wasm and provide the thin JavaScript wrapper. The template project already has it configured. You only need to use the wasm-bindgen macro on the Rust functions you want to make available.
Yes, if they share the same ABI.
When compiling to assembly, what matters is the ABI, or Application Binary Interface:
When you hear C is the Lingua Franca of programming languages, what it means is that any language that talks the C ABI1 can communicate with any other language that talks the C ABI.
Thus, whether targeting Windows on x64 or WebAssembly, what really matters is that both programs share the same convention (ABI) when talking to each other.
In your case, both Rust and C++ can talk C, so by communicating over a C API they can communicate on x86, x64, various ARM, ... and of course WASM.
1As a convention, the owner of a platform defines the C ABI for the platform, and all C compilers implement the defined ABI when targeting this platform. This means there are multiple, incompatible, C ABIs; however since an ABI only matters when interacting at the binary level, which only happens when executed on the same platform, in practice there's a single C ABI of relevance in any given situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With