Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ and Rust programs compiled to wasm interoperate somehow?

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?

like image 240
Nurbol Alpysbayev Avatar asked Dec 19 '19 15:12

Nurbol Alpysbayev


People also ask

Does Rust compile to Wasm?

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.

What is Rust WebAssembly?

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.

What is Wasm pack?

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.

How do I use JavaScript with Rust?

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.


1 Answers

Yes, if they share the same ABI.

When compiling to assembly, what matters is the ABI, or Application Binary Interface:

  • How are types represented in memory?
  • How are arguments passed to a function?
  • ...

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.

like image 129
Matthieu M. Avatar answered Sep 28 '22 06:09

Matthieu M.