You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何启用共享内存的Rust WASM构建需要更大内存?

Rust WASM共享内存构建的内存需求异常问题

我编写了一个尽可能精简的Rust WASM应用:

#![no_std]
use wasm_bindgen::prelude::wasm_bindgen;

#[wasm_bindgen]
pub async fn run() {
}

编译出的WASM文件大小仅27063字节,但运行时触发报错:

Uncaught (in promise)
LinkError: WebAssembly.instantiate(): memory import 26 is smaller than initial 18, got 17"
(当WebAssembly.Memory的initial设为小于18、maximum设为小于19时触发)

19×65536的内存远超出这个WASM文件的实际大小。

编译命令如下:

"build:wasm": "rustup run nightly wasm-pack build .. --target web --out-dir pkg -- -Z build-std=panic_abort,std",

相关配置:

[target.wasm32-unknown-unknown]
rustflags = [
    "--cfg=web_sys_unstable_apis",
    "-C", "target-feature=+atomics,+bulk-memory,+mutable-globals",
    "-C", "link-args=--shared-memory",
]

[unstable]
build-std = ["panic_abort", "std"]

配套的JS代码非常简单:

const memory = new WebAssembly.Memory({
        initial: 18,
        maximum: 19,
        shared: true
    });

不添加上述编译标志时,将initial/maximum设为1即可正常运行。我想知道:为什么启用共享内存的Rust WASM构建需要这么多内存?理论上只需要新增少量库代码才对?

对启用共享内存构建的WASM文件执行wasm2wat时输出:

000040e: error: memory may not be shared: threads not allowed

对普通WASM文件执行wasm2wat则输出大量内容,其中包含:

(memory (;0;) 17)
(export "memory" (memory 0))

内容的提问来源于stack exchange,提问作者user656449

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:42:25