WebAssembly LinkError: WebAssembly.instantiate(): mismatch in shared state of memory, declared = 0, imported = 1

WebAssembly LinkError: WebAssembly.instantiate(): mismatch in shared state of memory, declared = 0, imported = 1

我有一个简单的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”。

现在知道是因为wasm的memory需要声明为shared。 参见 the issue on Emscripten