Skip to content

Instantly share code, notes, and snippets.

@kfl
Last active April 16, 2023 23:36
Show Gist options
  • Save kfl/d5f1463ebe1b7107aeb02e2f4089a28a to your computer and use it in GitHub Desktop.
Save kfl/d5f1463ebe1b7107aeb02e2f4089a28a to your computer and use it in GitHub Desktop.
Javascript WebAssembly multiple modules
(module
(import "shared" "memory" (memory 1))
(import "shared" "table" (table 1 anyfunc))
(elem (i32.const 0) $read1) ;; set table[0] to read1 for indirect calling
(func $read1 (result i32)
i32.const 4
i32.load)
(func $read0 (result i32)
i32.const 0
i32.load)
(export "read0" (func $read0))
)
(module
(import "shared" "memory" (memory 1))
(import "shared" "table" (table 1 anyfunc))
(import "io" "print" (func $print (param i32)))
(import "module1" "read0" (func $m1_read0 (result i32)))
(type $void_to_i32 (func (result i32)))
(func (export "doIt")
(i32.store (i32.const 0) (i32.const 42)) ;; store 42 at address 0
(i32.store (i32.const 4) (i32.const 23)) ;; store 23 at address 4
(call $m1_read0)
(call $print)
(call_indirect (type $void_to_i32) (i32.const 0)) ;; indirect call to table[0]
(call $print))
)
// To be used with node.js
//
// First translate module1.wat and module2.wat to wasm:
// wat2wasm module1.wasm
// wat2wasm module1.wasm
//
// Then run the code with node:
// node runner.js
const fs = require('fs');
async function main() {
// functions to be exposed from Javascript to WASM
let env = {
io: {
print: console.log
},
shared: {
memory : new WebAssembly.Memory({ initial: 1 }),
table : new WebAssembly.Table({ initial: 1, element: "anyfunc" }) // for indirect calls
}
};
// load module1
let wasm1 = fs.readFileSync("module1.wasm");
let module1 = (await WebAssembly.instantiate(wasm1, env)).instance;
// add the exports from module1 to the environment
env["module1"] = module1.exports;
// // load module2
let wasm2 = fs.readFileSync("module2.wasm");
let module2 = (await WebAssembly.instantiate(wasm2, env)).instance;
// call doIt from module2
module2.exports.doIt();
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment