Skip to content

Instantly share code, notes, and snippets.

@jthomas
Created July 25, 2019 16:40
Show Gist options
  • Save jthomas/5de757fd36b3c6904e5c5f12c8264b41 to your computer and use it in GitHub Desktop.
Save jthomas/5de757fd36b3c6904e5c5f12c8264b41 to your computer and use it in GitHub Desktop.
Using WebAssembly Modules from IBM Cloud Functions (Apache OpenWhisk)
$ emcc -s WASM=1 -s SIDE_MODULE=1 -s EXPORTED_FUNCTIONS="['_add']" -O1 add.c -o add.wasm
$ zip action.zip index.js add.wasm package.json
updating: index.js (deflated 52%)
updating: add.wasm (deflated 7%)
updating: package.json (deflated 15%)
$ ibmcloud wsk action create wasm action.zip --kind nodejs:10
ok: created action wasm
$ ibmcloud wsk action invoke wasm -r -p a 2 -p b 2
{
    "sum": 4
}
int add(int a, int b) {
return a + b;
}
'use strict';
const fs = require('fs');
const util = require('util')
const WASM_MODULE = 'add.wasm'
let wasm_instance
async function load_wasm(wasm_module) {
if (!wasm_instance) {
const bytes = fs.readFileSync(wasm_module);
const memory = new WebAssembly.Memory({initial: 1});
const env = {
__memory_base: 0,
memory: new WebAssembly.Memory({
initial: 1
})
}
const { instance, module } = await WebAssembly.instantiate(bytes, { env });
wasm_instance = instance
}
return wasm_instance.exports._add
}
exports.main = async function ({ a = 1, b = 1 }) {
const add = await load_wasm(WASM_MODULE)
const sum = add(a, b)
return { sum }
}
{
"name": "wasm",
"version": "1.0.0",
"main": "index.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment