Hi All,
I am investigating how to run C code as WebAssembly in the browser.
To test it out I made a small C program:
#include <emscripten.h>
int EMSCRIPTEN_KEEPALIVE add2(int x, int y) {
return x+2*y;
}
And then I compiled it using:
emcc test.c -s WASM=1 -s ONLY_MY_CODE=1
This produced a file a.out.wasm which is 256 bytes (which seems reasonable) and a file a.out.js which is 85K (which seems very large).
Further, the a.out.wasm file has the text "add2" inside, so this seemed promising!
<script>
function fetchAndInstantiate(url, importObject) {
return fetch(url).then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, importObject)
).then(results =>
results.instance
);
}
importObject={}
fetchAndInstantiate('a.out.wasm', importObject).then(function(instance) {
console.log(instance.exports._add2(2,4));
})
</script>
Unfortunately this did not work - I got this error in the JavaScript console:
TypeError: import object field 'env' is not an Object
Troubleshooting a bit further I tried this html:
<script>
fetch('a.out.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.compile(bytes)
).then(function(mod) {
var imports = WebAssembly.Module.imports(mod);
console.log(imports[0]);
});
</script>
Which gave this output:
Object { module: "env", name: "STACKTOP", kind: "global" }
Debugging a bit futher it seemed like the webassembly needs an env in importObject with a bunch of values in it, including this STACKTOP.
My questions are:
1) Can emscripten produce a webassembly file that does not need such values to be set externally?
2) If emscripten cannot, is there a recommend way to get less than 85K of JavaScript to set reasonable values?
I used FireFox version 56 and emscripten version 1.37.22.
Best,
Christian