試一試
(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 可以與指定記憶體一起使用的版本。