7

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?

Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89
  • I don't think you can call directly functions from one module to the other. For that to be possible a common interface would need to be defined, like when calling methods in a shared library. I am not aware of such interface, so you probably need to bridge the modules with javascript code. – Tomáš Zato Dec 19 '19 at 15:58
  • @TomášZato-ReinstateMonica thank you. Bridging the two with JS is fine 99% of the time, until it becomes the bottleneck.... – Nurbol Alpysbayev Dec 19 '19 at 16:15

1 Answers1

10

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.

1 As 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.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • Thanks! Excellent answer. For a long time I didn't really understand what ABI is. You made it really simple for me: `How are types represented in memory?`. I did see the C bindings for Rust (just didn't write them myself), so I know they exist and are possible. So I think I should learn that area. – Nurbol Alpysbayev Dec 19 '19 at 16:11
  • @NurbolAlpysbayev By the way, if you make this work in some self-contained answer, it would be an awesome self-answered question to post here. – Tomáš Zato Dec 19 '19 at 17:08