Skip to content

Instantly share code, notes, and snippets.

@alinz
Created September 25, 2019 19:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alinz/830a2d2268d33d47166431490c850eb6 to your computer and use it in GitHub Desktop.
Save alinz/830a2d2268d33d47166431490c850eb6 to your computer and use it in GitHub Desktop.
Compile Zig to WebAssembly and run it in Node.js
const fs = require("fs");
const content = fs.readFileSync("./test.wasm");
WebAssembly.compile(content)
.then(module => {
const imports = {
env: {
memoryBase: 0,
tableBase: 0,
memory: new WebAssembly.Memory({ initial: 256 }),
table: new WebAssembly.Table({ initial: 0, element: "anyfunc" })
}
};
const instance = new WebAssembly.Instance(module, imports);
console.log(instance.exports.addInc(1, 2));
})
.catch(e => {
console.error(e);
});
build:
zig build-exe --name test.wasm -target wasm32-freestanding --release-small test.zig
export fn addInc(a: i32, b: i32) i32 {
return a + b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment