Skip to content

Instantly share code, notes, and snippets.

@dlmanning
Last active Oct 29, 2019
Embed
What would you like to do?
const fs = require('fs');
const mathWASM = fs.readFileSync('./math.wasm');
const mainWASM = fs.readFileSync('./main.wasm');
async function main() {
// Both modules will share this table
const table = new WebAssembly.Table({
element: "anyfunc",
initial: 3,
})
imports = { env: { table } }
const mathModule = await WebAssembly.instantiate(mathWASM, imports);
// The math module populates the table like this:
// | $add | $sub | $mul |
const mainModule = await WebAssembly.instantiate(mainWASM, imports);
// main calls the function at zero index in the table: $add
console.log(mainModule.instance.exports.foo(7, 3)); // 10
swapTableIndices(table, 0, 1);
// now: | $sub | $add | $mul |
console.log(mainModule.instance.exports.foo(7, 3)); // 4
swapTableIndices(table, 0, 2);
// now | $mul | $add | $sub |
console.log(mainModule.instance.exports.foo(7, 3)); // 21
}
main();
// WASM is not yet able to modify the table internally
// aside from adding functions during initilization
function swapTableIndices(table, i, j) {
const f = table.get(i);
const g = table.get(j);
table.set(i, g);
table.set(j, f);
}
(module
(type (;0;) (func (param i32 i32) (result i32)))
(import "env" "table" (table (;0;) 1 funcref))
(func (;0;) (type 0) (param i32 i32) (result i32)
local.get 0
local.get 1
i32.const 0 ;; index of function in table
call_indirect (type 0) (;type of function being called;))
(memory (;0;) 2)
(export "foo" (func 0)))
(module
(type (;0;) (func))
(type (;1;) (func (param i32 i32) (result i32)))
(import "env" "table" (table (;0;) 3 funcref))
(func $add (;0;) (type 1) (param i32 i32) (result i32)
local.get 1
local.get 0
i32.add)
(func $sub (;1;) (type 1) (param i32 i32) (result i32)
local.get 0
local.get 1
i32.sub)
(func $mul (;2;) (type 1) (param i32 i32) (result i32)
local.get 0
local.get 1
i32.mul)
(memory (;0;) 2)
(export "memory" (memory 0))
(elem (;0;)
(i32.const 0) ;; table offset
$add $sub $mul;; add funcs to table
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment