试一试
(module
(import "console" "log" (func $log (param i32)))
(memory 2)
(func $main
memory.size ;; get the memory size
call $log ;; log the result
)
(start $main)
)
const url = "{%wasm-url%}";
await WebAssembly.instantiateStreaming(fetch(url), { console });
语法
获取默认内存的大小
wat
;; Get the number of pages in the default memory
memory.size
;; The number of pages is now added at top of stack
获取指定内存的大小(如果支持多内存)
wat
;; Size of memory with index 1
memory.size (memory 1)
;; Size of memory named $memory2
memory.size (memory $memory2)
指令和操作码
| 指令 | 二进制操作码 |
|---|---|
memory.size |
0x3f |
示例
获取默认内存的大小
添加到 Wasm 模块的第一个内存是默认内存,索引为 0。我们可以通过调用 memory.size 来获取此内存的页面数量。
下面的代码显示了一个演示此的 WAT 文件
wat
(module
(import "console" "log" (func $log (param i32)))
(memory 1 2) ;; default memory with one page and max of 2 pages
(func $main
;; get size
memory.size
call $log ;; log the result (1)
;; grow default memory by 1 page
i32.const 1
memory.grow
;;get size again
memory.size
call $log ;; log the result (2)
)
(start $main) ;; call immediately on loading
)
上面我们不需要在 memory.size 指令中指定内存索引,但也可以通过默认内存的内存索引(0)来指定。
wat
memory.size (memory 0)
为了完整起见,我们可以使用上面文件 size.wasm 的编译版本,其代码与下面所示类似(log 函数被导入到模块中,并由模块调用)。
js
start();
async function start() {
const importObject = {
console: {
log(arg) {
console.log(arg);
},
},
};
const result = await WebAssembly.instantiateStreaming(
fetch("size.wasm"),
importObject,
);
}
start();
获取特定内存的大小
随着内存被定义在 Wasm 模块中,它们会从零开始按顺序分配索引号。您可以通过在 memory.size 指令之后指定 memory 指令和所需的索引或名称(如果它有名称)来获取特定内存的大小。如果您不指定特定内存,则会使用索引为 0 的默认内存。
下面的模块展示了如何直接通过索引和名称引用内存。
wat
(module
(import "console" "log" (func $log (param i32)))
(memory 1 2) ;; Default memory with one page and max of 2 pages
(memory $memory1 2 4) ;; Memory with index 1, initial 2 page, max 4 pages
(func $main
;; Get size for memory by index
memory.size (memory 1)
call $log ;; log the result (2)
;; Get size for memory by memory name
memory.size (memory $memory1)
call $log ;; log the result (2)
)
(start $main)
)
可以使用与第一个示例相同的 JavaScript 代码加载 WAT 文件。
规范
| 规范 |
|---|
| 未知规范 # syntax-instr-memory |
浏览器兼容性
webassembly.api.Memory
加载中…
webassembly.multiMemory
加载中…
注意: multiMemory 兼容性表指示了 size 可以与指定内存一起使用的版本。