WASM 内存模型与管理
了解 WebAssembly 的线性内存模型,以及 WASM 模块如何分配、访问和管理内存
WASM 内存模型与管理 是 CoddyKit 上的免费 WebAssembly (WASM) for High Performance Apps 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebAssembly (WASM) for High Performance Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
WASM Linear Memory: The Basics
WebAssembly uses a linear memory model. Think of it as a single, large, contiguous array of bytes, similar to how traditional programs manage memory.
- This memory is separate from JavaScript's memory.
- It's accessed by WASM modules as a flat address space, starting from address 0.
- All data (integers, floats, strings, arrays) lives within this single memory block.
The `WebAssembly.Memory` Object
In JavaScript, WASM memory is represented by the WebAssembly.Memory object. This object holds the actual memory buffer.
You can create it:
- When instantiating a WASM module, it can declare and create its own memory.
- You can also pass an existing
WebAssembly.Memoryinstance from JavaScript to the module.
const memory = new WebAssembly.Memory({
initial: 1, // Start with 1 page (64KB)
maximum: 10 // Max allowed 10 pages
});
// This 'memory' object is then passed to the
// WASM module during instantiation.Memory Pages: The Unit of Size
WASM memory is organized into fixed-size units called pages. Each page is exactly 64 KiB (65,536 bytes) in size.
- The
initialandmaximumproperties ofWebAssembly.Memoryare always defined in terms of pages. - A WASM module might start with just 1 page, growing its memory as needed for efficiency.
- This page-based system allows for efficient memory management and protection.
JavaScript's View into Memory
JavaScript cannot directly access WASM's linear memory using raw pointers. Instead, it gets an ArrayBuffer view of the memory.
You then use TypedArrays (like Uint8Array, Int32Array, Float64Array) or a DataView to read and write specific data types at specific offsets within that ArrayBuffer.
const memoryBuffer = instance.exports.memory.buffer;
const uint8Array = new Uint8Array(memoryBuffer); // Byte-level view
const int32Array = new Int32Array(memoryBuffer); // 4-byte integer viewAllocating Memory in C/WASM
When you compile C/C++ to WASM, functions like malloc allocate memory from WASM's linear memory. This example shows a C function that allocates space for an integer array.
It returns a memory offset (an integer) rather than a direct pointer, which JavaScript then uses.
#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#else
#define EMSCRIPTEN_KEEPALIVE
#endif
EMSCRIPTEN_KEEPALIVE
int* allocate_int_array(int size) {
int* arr = (int*) malloc(size * sizeof(int));
if (arr) {
for (int i = 0; i < size; ++i) {
arr[i] = i * 10; // Initialize with some data
}
}
return arr; // Returns memory offset
}
int main() {
// Main function is often a placeholder for WASM modules
return 0;
}Accessing C-Allocated Memory from JS
After WASM allocates memory (e.g., using allocate_int_array), JavaScript can access it using the returned offset and a TypedArray.
The offset tells JS exactly where in the underlying ArrayBuffer the allocated data begins, allowing precise read/write operations.
// Assuming 'instance' is your WASM module instance
const offset = instance.exports.allocate_int_array(5);
const memoryBuffer = instance.exports.memory.buffer;
// Create an Int32Array view starting at the offset
const intArray = new Int32Array(memoryBuffer, offset, 5);
console.log(intArray[0]); // Expected: 0
console.log(intArray[1]); // Expected: 10
// ... and so onDeallocating Memory with `free`
Just like in C, it's crucial to deallocate memory you've allocated using malloc to prevent memory leaks. The free function in WASM works similarly, releasing the memory back to the WASM runtime.
This C function frees a previously allocated memory block using its offset.
#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#else
#define EMSCRIPTEN_KEEPALIVE
#endif
EMSCRIPTEN_KEEPALIVE
void free_wasm_memory(int* ptr) {
if (ptr) {
free(ptr); // Release the memory block
}
}
int main() {
return 0;
}Dynamically Growing Memory
WASM memory isn't fixed; it can grow! The memory.grow(numPages) method, exposed on the WebAssembly.Memory object, allows you to increase the memory size by a specified number of pages.
- This method returns the previous number of pages.
- If
growfails (e.g., exceeds themaximum), it returns -1. - Important: Existing TypedArray views become invalid after a grow operation; you must create new ones from the updated
memory.buffer.
const currentPages = instance.exports.memory.grow(1); // Add 1 page
console.log(`Memory grew from ${currentPages} pages.`);
// After growing, always recreate TypedArray views!
const newMemoryBuffer = instance.exports.memory.buffer;
const newUint8Array = new Uint8Array(newMemoryBuffer);Memory Management Check
Which of the following statements about WebAssembly's linear memory model are TRUE?
Recap: WASM Memory Management
We've explored WebAssembly's linear memory model, a foundational concept for high-performance applications.
- WASM memory is a contiguous byte array, separate from JS memory.
- It's managed by the
WebAssembly.Memoryobject and organized into 64 KiB pages. - JavaScript interacts with this memory using
ArrayBufferandTypedArraysto read and write data. - C functions like
mallocandfreeoperate within this WASM memory space, with `malloc` returning an offset. - Memory can be dynamically increased using
memory.grow(), but requires re-creating JS views.
Understanding these concepts is key to efficient data exchange and memory handling in WASM applications.
用 AI 导师学习 WebAssembly (WASM) for High Performance Apps — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「WASM 内存模型与管理」课时是免费的吗?
是的 — 「WASM 内存模型与管理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebAssembly (WASM) for High Performance Apps 课程的其余内容,请升级到 CoddyKit PRO。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。
「WASM 内存模型与管理」这节课中我会学到什么?
了解 WebAssembly 的线性内存模型,以及 WASM 模块如何分配、访问和管理内存 你通过在浏览器中直接运行的动手代码来练习 WebAssembly (WASM) for High Performance Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 WebAssembly (WASM) for High Performance Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 WebAssembly (WASM) for High Performance Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「WASM 内存模型与管理」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 WebAssembly (WASM) for High Performance Apps 课中编写并运行代码吗?
能。每节 WebAssembly (WASM) for High Performance Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。