How can I wrap the printf() function with console.log? I want to write a small webassembly demo but I can't interprete the following js console output. I compiled the C code with Clang to wasm file.
C Code:
#include <stdio.h>
int main(void)
{
printf ("test");
return 0;
}
JS Code:
const config = {
env: {
memory_base: 0,
table_base: 0,
memory: new WebAssembly.Memory({
initial: 256,
}),
table: new WebAssembly.Table({
initial: 0,
element: 'anyfunc',
}),
printf: msg => console.log(msg),
}
}
fetch('test.wasm')
.then(response =>
response.arrayBuffer()
)
.then(bytes => {
return WebAssembly.instantiate(bytes, config);
})
.then(results => {
var { main } = results.instance.exports;
main();
});
The console output is always: "1024" , independent of the printf() input parameter. But I want to get the string "test" as output. How to interprete this result? Is it a pointer to a memory address? When I use printf('a') I get 97 as console output, the ascii representation of the char.
Solution:
let buffer;
const config = {
env: {
memory_base: 0,
table_base: 0,
memory : new WebAssembly.Memory({ initial: 256}),
table: new WebAssembly.Table({
initial: 0,
element: 'anyfunc',
}),
printf: index=> {
let s = "";
while(true){
if(buffer[index] !== 0){
s += String.fromCharCode(buffer[index]);
index++;
}else{
console.log(s);
return;
}
}
}
}
};
fetch(url)
.then(response =>{
return response.arrayBuffer();
})
.then(bytes => {
return WebAssembly.instantiate(bytes, config);
})
.then(results => {
let { main } = results.instance.exports;
buffer = new Uint8Array(results.instance.exports.memory.buffer);
main();
});