As a web developer with a decent amount of experience in JavaScript, one of the most crucial aspects of utilizing WebAssembly(Wasm) in your web applications is knowing how to 'call' Wasm functions from JavaScript. This ability fosters a seamless integration of performant Wasm modules into an existing JavaScript codebase.
For instance, imagine building a web application that performs complex computations, such as a real-time sports statistics dashboard. Performance is critical in such applications, and dropping in a Wasm module for heavy lifting would be perfect. But how do you make it all work together? That's where interfacing JavaScript to WebAssembly comes in.
Let's consider that we have already compiled our C++ code into a Wasm module. We'll use a simple addition function as an example:
1#include <emscripten/emscripten.h>
2
3extern "C" {
4 int EMSCRIPTEN_KEEPALIVE add(int a, int b) {
5 return a + b;
6 }
7}
This compiled Wasm file(add.wasm
) exports a function add()
. To use it in JavaScript, we first need to fetch and instantiate the Wasm module. Here's how:
1const runWasm = async () => {
2 const response = await fetch('add.wasm');
3 const buffer = await response.arrayBuffer();
4 const { instance } = await WebAssembly.instantiate(buffer);
5 console.log('Addition result: ', instance.exports.add(5, 3));
6};
7runWasm();
In this JavaScript code snippet, we fetch the Wasm binary module add.wasm
over the network, then instantiate it into an instance. The instance exposes the exported WebAssembly functions, in this case add()
, which we can then call just like any other JavaScript function within our application.
xxxxxxxxxx
using namespace std;
extern "C" {
int EMSCRIPTEN_KEEPALIVE add(int a, int b) {
return a + b;
}
}