现在我知道这是因为wasm的
我有一个简单的c代码:
// accumulate.c
int arr[];
int accumulate(int start, int end) {
int sum = 0;
for(int i = start; i < end; i++) {
sum += arr[i];
}
return sum;
}
将其编译为wasm:
$ emcc accumulate.c -O3 -s SIDE_MODULE -o accumulate.wasm
以下HTML运行良好:
<!-- accumulate.html -->
<script>
const memory = new WebAssembly.Memory({
initial: 1,
});
const importObj = {
env: {
memory: memory,
__memory_base: 0,
g$arr: () => {}
}
};
(async () => {
const res = await fetch("accumulate.wasm");
const wasmFile = await res.arrayBuffer();
const module = await WebAssembly.compile(wasmFile);
const instance = await WebAssembly.instantiate(module, importObj);
const arr = new Uint32Array(memory.buffer);
for (let i = 0; i < 10; i++) {
arr[i] = i;
}
const sum = instance.exports.accumulate(0, 10);
console.log("accumulate from 0 to 10: " + sum);
})();
</script>
但是,如果我将memory
设置为shared: true
:
const memory = new WebAssembly.Memory({
initial: 1,
maximum: 1,
shared: true
});
Chrome显示错误";LinkError:WebAssembly.instantiate((:内存的共享状态不匹配,声明=0,导入=1";。
memory
需要声明为shared
。查看Emscripten 上的问题