I'm trying to pass a value from JavaScript to WASM, but it's not working. Here's my C code:
extern int x;
int foo() {
return x;
}
In JavaScript, I instantiate the module and set x equal to 5:
var importObj = {
env: {
memory: new WebAssembly.Memory({initial: 256, maximum: 256}),
_x: 5
}
};
WebAssembly.instantiateStreaming(fetch('test.wasm'), importObj)
.then(result =>
console.log('Output: ' + result.instance.exports._foo())
);
This doesn't produce any errors, but the logged message is Output: 0
instead of Output: 5
. Any ideas?
答案 0 :(得分:1)
你用什么来编译你的C代码到wasm?我试图让这个工作在https://webassembly.studio上,并发现函数foo
从内存位置0
加载值。所以我能够通过从JS:
Output: 5
WebAssembly.instantiateStreaming(fetch('test.wasm'), importObj)
.then(result => {
const mem = new Uint32Array(result.instance.exports.memory.buffer)
mem[0] = 5
console.log('Output: ' + result.instance.exports._foo())
});
说实话,我希望extern int x
成为可以通过importObj
传递的wasm的导入全局。我希望这仍然有助于走上正确的道路。
答案 1 :(得分:1)
当前的lld实现在链接时不支持未定义的数据符号。如果您通过--allow-undefined
,您将得到未定义的符号,其地址为0。
我们一直在讨论添加对导入数据符号的支持:https://github.com/WebAssembly/tool-conventions/issues/48