WebAssembly: Running C++ in the Browser at Near-Native Speed
2017 is a landmark year for the web. For over two decades, JavaScript was the only language you could run in a browser. But now, with the release of WebAssembly (Wasm), that has changed. Wasm is a binary instruction format designed as a compilation target for languages like C++ and Rust, allowing for near-native performance on the web.
Why do we need it?
JavaScript is amazing, but it's a dynamic language. Even with modern JIT engines, it struggles with heavy computational tasks like video encoding, 3D games, and image processing. WebAssembly provides a predictable, low-level execution environment.
Compiling C++ to Wasm
Using Emscripten, we can take an existing C++ function and compile it into a .wasm file.
// math.cpp
#include <emscripten.h>
extern "C" {
EMSCRIPTEN_KEEPALIVE
int add(int a, int b) {
return a + b;
}
}
Compile it with:
emcc math.cpp -s WASM=1 -o math.js
Loading Wasm in JavaScript
Wasm isn't meant to replace JavaScript; it's meant to work with it. Here is how we load and call our C++ function in 2017:
fetch('math.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes)
).then(results => {
const add = results.instance.exports.add;
console.log('10 + 20 =', add(10, 20));
});
Linear Memory: The Interop Challenge
Wasm and JS share a Linear Memory (an ArrayBuffer). If you want to pass a string or a complex object from JS to Wasm, you can't just pass the object. You have to write the data into the shared memory and pass the pointer (the offset) to the Wasm function.
// Writing a string to Wasm memory
function writeStringToWasm(str, wasmInstance) {
const encoder = new TextEncoder();
const bytes = encoder.encode(str);
const ptr = wasmInstance.exports.malloc(bytes.length + 1);
const heap = new Uint8Array(wasmInstance.exports.memory.buffer);
heap.set(bytes, ptr);
heap[ptr + bytes.length] = 0; // Null terminator
return ptr;
}
WebAssembly is opening the door for complex desktop-class applications to run in the browser. AutoCAD, Unity, and Google Earth are already making the move. The web is becoming the ultimate universal platform.
Aunimeda builds modern web frontends - from single-page applications to complex multi-locale sites.
Contact us to discuss your frontend project. See also: Web Development, Corporate Website Development