Mark As Completed Discussion

One of the best things about WebAssembly (Wasm) is how it can work seamlessly with JavaScript. To understand this, let's create a C++ function to compile to a Wasm module, and then interact with it through JavaScript.

First, here's a simple C++ function we will use:

TEXT/X-C++SRC
1#include <emscripten.h>
2
3extern "C" {
4
5  EMSCRIPTEN_KEEPALIVE
6  int add_two_nums(int a, int b) {
7    return a + b;
8  }
9
10}

This function uses the extern "C" declaration to avoid name mangling, and EMSCRIPTEN_KEEPALIVE to make the function visible to the Wasm module.

After compiling this to a Wasm module, we would use JavaScript to load and run it. Here's a general example of how one might do this with WebAssembly's JavaScript API:

JAVASCRIPT
1WebAssembly.instantiateStreaming(fetch('add_two_nums.wasm'))
2.then(obj => {
3  let result = obj.instance.exports.add_two_nums(5, 3);
4  console.log(result);  // Outputs: 8
5});

This JavaScript code first fetches the Wasm module with fetch(), then compiles and instantiates it with WebAssembly.instantiateStreaming(). It then calls the add_two_nums() function exported from the Wasm instance, logs the result, and voila - we have JavaScript calling a C++ function compiled to Wasm!

This ability to interface seamlessly with JavaScript is one of the aspects of Wasm that opens up numerous possibilities, particularly for performance optimization and code reuse in web apps. But as with any program, Wasm modules can sometimes contain errors or unexpected behavior, which is where debugging tools and techniques come into play, as we will explore in the next sections.