store: Wasm 文本指令

store 内存指令用于将堆栈中的数字存储到内存中。

有用于将 i32i64f32f64 存储到内存中的 store 指令。对于整数,有单独的指令变体,用于将宽类型数字存储到内存中的窄类型数字。例如,您可以使用 i32.store8 将 32 位数字存储到内存中的 8 位槽中。如果数字不适合较窄的数字类型,则会发生环绕。所有变体均在下方列出

试一试

(module

  (memory $memory 1)
  (export "memory" (memory $memory))

  (func (export "store_in_mem") (param $num i32)
    i32.const 0
    local.get $num

    ;; store $num at position 0
    i32.store
  )

)
const url = "{%wasm-url%}";
const result = await WebAssembly.instantiateStreaming(fetch(url));

const store_in_mem = result.instance.exports.store_in_mem;
const memory = result.instance.exports.memory;

store_in_mem(100);

const dataView = new DataView(memory.buffer);
const first_number_in_mem = dataView.getUint32(0, true);

console.log(first_number_in_mem);
// Expected output: 100

语法

存储到默认内存

wat
;; Store value in default memory at particular offset
i32.const 0 ;; stack variable with offset in memory to store the number
i32.const 20 ;; stack variable with the number to store
i32.store ;; store in default memory

;; Store using S-function (same values and offset)
(i32.store (i32.const 0) (i32.const 20))

存储到指定内存(如果支持多内存)

wat
;; Store in memory referenced by its index
i32.const 0 ;; offset in memory to store the number
i32.const 20 ;; the number to store
i32.store (memory 2)  ;; store in memory with index 2

;; Store in memory referenced by its name
i32.const 0 ;; offset to store the number
i32.const 20 ;; the number to store
i32.store (memory $memoryName)  ;; store in memory with name "$memoryName"

;; Store in same memory using an S function
(i32.store (memory $memoryName) (i32.const 0) (i32.const 20))

指令和操作码

指令 二进制操作码
i32.store 0x36
i64.store 0x37
f32.store 0x38
f64.store 0x39
i32.store8 0x3a
i32.store16 0x3b
i64.store8 0x3c
i64.store16 0x3d
i64.store32 0x3e

规范

规范
未知规范
# syntax-instr-memory

浏览器兼容性

webassembly.api.Memory

webassembly.multiMemory

注意: multiMemory 兼容性表显示了 store 可用于指定内存的版本。