WebAssembly first-step

JavaScript code
const buf = await (await fetch("./test.wasm")).arrayBuffer(); const result = await WebAssembly.instantiate(buf); const ex = result.instance.exports; const mem = ex.memory.buffer; const memoffset = ex.getMemory(); const memlen = ex.getMemorySize(); const data = new Uint32Array(mem, memoffset, memlen); print("mem len: " + data.length); for (let i = 0; i < data.length; i++) { data[i] = i + 1; print("set [" + i + "] = " + (i + 1)); } print("calc: " + ex.calc());
Output on the browser
C code
#define SIZE 10 int mem[SIZE]; int* getMemory() { return mem; } int getMemorySize() { return SIZE; } int calc() { int sum = 0; for (int i = 0; i < SIZE; i++) { sum += mem[i]; } return sum; }
setup
$ brew install llvm
command to compile
$ /usr/local/opt/llvm/bin/clang --target=wasm32 -O3 -nostdlib -Wl,--no-entry -Wl,--export-all \ test.c -o test.wasm
API: WebAssembly / wasm
APP: CC BY fukuno.jig.jp