我正在编写一个小型C程序,旨在编译为wasm w/emcc
并在Web浏览器中运行。因为wasm导出的函数只能接受简单的数字值作为参数输入和返回值,所以我需要在JavaScript API和编译的WebAssembly代码之间共享内存,以访问更复杂的数据类型,如字符串或数组。问题是我不能在我的生活中弄清楚如何从我的C程序中访问WebAssembly linear memory。如何从C/C++访问WebAssembly线性内存
我的最终目标是能够读取在我的C程序中使用JavaScript初始化的字符串,然后还可以在Web浏览器的JavaScript代码中读取在我的C程序中修改/初始化的字符串。
这里是什么,我试图做一个简单的例子:
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让我的方式的一部分但是,我仍然不明白如何从我的C代码中的WebAssembly内存缓冲区读取/写入数据。