Is it possible to retrieve a JavaScript string from a WebAssembly function?
https://dev.to/azure/passing-strings-from-c-to-javascript-in-web-assembly-1p01 - not functional
C
#include <stdio.h>
#include <string.h>
void jsPrintString(const char *s, uint16_t len);
void print() {
const char* str = "Hello from C++!";
jsPrintString(str, strlen(str));
}
Compiler:
emcc -Os start.c -s STANDALONE_WASM -s EXPORTED_FUNCTIONS="['_hello']" -s ERROR_ON_UNDEFINED_SYMBOLS=0 -Wl,--no-entry -o "test.wasm"
Javascript:
const memory = new WebAssembly.Memory({ initial: 1 });
function handlePrintString (offset, length) {
console.log(offset, length);
const bytes = new Uint8Array(memory.buffer, offset, length);
const string = new TextDecoder('utf8').decode(bytes);
console.log(string); //empty ???????????????????????????????????
}
const importObject = {
env: {
jsPrintString: handlePrintString,
memory: memory
},
js: { mem: memory }
};
WebAssembly.instantiateStreaming(fetch('/js/test.wasm'), importObject)
.then(obj => {
console.log(obj.instance.exports);
console.log(obj.instance.exports.print());
});
memory ArrayBuffer [0,0,0,0,0,0,0,0,0,0,0.....] ???