Skip to content

Instantly share code, notes, and snippets.

@mattcollier
Last active December 10, 2017 15:39
Show Gist options
  • Save mattcollier/f467013254f0cd8c0782822a20c0bb6f to your computer and use it in GitHub Desktop.
Save mattcollier/f467013254f0cd8c0782822a20c0bb6f to your computer and use it in GitHub Desktop.
nodejs WebAssembly basic example
# emcc (Emscripten gcc/clang-like replacement) 1.37.22 ()
emcc -o index.js hello4.c -O3 -s WASM=1 -s NO_EXIT_RUNTIME=1 -s SIDE_MODULE=1
#include <emscripten/emscripten.h>
int main(int argc, char ** argv) {
}
#ifdef __cplusplus
extern "C" {
#endif
EMSCRIPTEN_KEEPALIVE
int doubler(int x) {
int z = 2 * x;
return z;
}
#ifdef __cplusplus
}
#endif
// nodejs v8.9.3
'use strict';
const env = {
memoryBase: 0,
tableBase: 0,
memory: new WebAssembly.Memory({initial: 256}),
table: new WebAssembly.Table({initial: 0, element: 'anyfunc'})
};
const code = require('fs').readFileSync('index.wasm');
WebAssembly.instantiate(code, {env}).then(mod => {
console.log('DOUBLER', mod.instance.exports._doubler(7));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment