I am learning with webassembly but I can not run basic simple app. I tried many possibilities, and none of them is working. My last aproach is this.
I am coding on Windows 10 so I installed emsdk from github.
git clone https://github.com/emscripten-core/emsdk.git
emsdk install latest
emsdk activate latest
emsdk_env.bat
I programmed this simple C++ code:
extern "C" {
int sum(int a, int b) {
return a + b;
}
}
I compiled my source code like this:
em++ cpp-sources/Sum/sum.cpp -o sum/sum.js -s MODULARIZE
In javscript Node, I have this function:
public getSum(){
const factory = require(__dirname + "/sum/sum.js");
factory().then((instance) => {
const sum = instance.sum as CallableFunction;
console.log(sum(5, 6));
});
}
After all my tries, it is still saying:
TypeError: sum is not a function
I also tried different approaches of calling wasm in Node. For example this one:
public getSum(){
const fs = require('fs');
const wasmBuffer = fs.readFileSync(__dirname + "/sum/sum.wasm");
WebAssembly.instantiate(wasmBuffer).then(wasmModule => {
const sum = wasmModule.instance.exports.sum as CallableFunction;
const result = sum(5, 6);
console.log(result);
});
}
Result is same.
I have also another problem, that I can not include <emscripten.h> library in my C++ code.
Thank you for any ideas.
EDIT: I tried to compile C++ code to wasm with this:
em++ --no-entry cpp-sources/Sum/sum.cpp -o sum/sum.wasm -s LINKABLE=1 -s EXPORT_ALL=1 -O2
Now when I run my typescript Node code, it has not error I mentioned before but new one:
[TypeError: WebAssembly.instantiate(): Imports argument must be present and must be an object]
I tried to update code as this:
public async getSum(){
const binary = readFileSync(__dirname + "/sum/sum.wasm");
const wasm = await WebAssembly.compile(binary);
const importObject = {
env: {
memory: new WebAssembly.Memory({initial:10,maximum:10})
}
};
WebAssembly.instantiate(wasm, importObject).then(instance => {
const sum = instance.exports._sum as CallableFunction;
const result = sum(5, 6);
console.log(result);
});
}
Now it has this error:
WebAssembly.instantiate(wasm, importObject).then(instance => {
^
TypeError: WebAssembly.instantiate(): Import #257 module="wasi_snapshot_preview1" error: module is not an object or function
at CalculatorService.<anonymous>