Created
September 25, 2019 19:26
-
-
Save alinz/830a2d2268d33d47166431490c850eb6 to your computer and use it in GitHub Desktop.
Compile Zig to WebAssembly and run it in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
build: | |
zig build-exe --name test.wasm -target wasm32-freestanding --release-small test.zig |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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