I'm writing a small C program intended to be compiled to wasm w/ emcc
and run in a web browser. Because wasm exported functions can only accept simple number values as parameter inputs and return values, I need to share memory between the JavaScript API and the compiled WebAssembly code in order to access more complex data types like strings or char
arrays. The problem is that I can't for the life of me figure out how to access WebAssembly linear memory from inside of my C program.
My ultimate goal is to be able to read strings initialized in JavaScript inside of my C program, and then also read strings that are modified/initialized in my C program back in the web browser's JavaScript code.
Here is a basic example of what I'm trying to do:
main.js
const importObject = {
'env': {
'memoryBase': 0,
'tableBase': 0,
'memory': new WebAssembly.Memory({initial: 256}),
'table': new WebAssembly.Table({initial: 0, element: 'anyfunc'})
}
}
// using the fetchAndInstantiate util function from
// https://github.com/mdn/webassembly-examples/blob/master/wasm-utils.js
fetchAndInstantiate('example.wasm', importObject).then(instance => {
// call the compiled webassembly main function
instance.exports._main()
console.log(importObject.env.memory)
})
example.c
int main() {
// somehow access importObject.env.memory
// so that I can write a string to it
return 0;
}
This question gets me part of the way there, however, I still don't understand how to read/write from the WebAssembly memory buffer in my C code.