Hey folks,
This post continues our multi-part series on WebAssembly. See the other parts here.
Now that we understand WebAssembly's basics, let's explore its architecture. Key components include:
A WebAssembly module is a compiled code unit containing functions, memory, tables, and other resources needed for execution. Each module is self-contained and independently instantiable. It's essentially a .wasm
file. Modules support importing and exporting functions and memory, enabling modular programming and integration with other web technologies.
WebAssembly runs in a secure, isolated, sandboxed environment within a host (like a browser or Node.js). This environment restricts access to the host system, enhancing security. Access to resources requires explicit requests. The execution environment includes a WebAssembly runtime managing module loading, verification, memory, and instruction execution.
WebAssembly uses a stack-based virtual machine. Instructions manipulate data on a stack. Here's a simple example:
<code>( func $add(param $a i32) (param $b i32) (result i32) local.get $a local.get $b i32.add )</code>
This function adds two 32-bit integers. The stack machine's execution steps are:
$a
onto the stack.$b
onto the stack.$a
and $b
, add them.WebAssembly's linear memory model is a contiguous, growable byte array—the HEAP for WebAssembly programs. It's indexed by byte offsets, allowing direct access to specific locations.
For instance, storing two 8-bit numbers (10 and 16) at addresses 0 and 1 respectively:
Data can be accessed using different bit views; consistency is key to avoid conflicts. JavaScript accesses memory via the WebAssembly.Memory
interface. For example:
<code class="language-javascript">const memory = new WebAssembly.Memory({ initial: 10, maximum: 100 });</code>
This allocates 640kB (minimum) of memory (1 page = 64kB). Shared memory allows multi-threaded access. setValue(ptr, value, type)
and getValue(ptr, type)
simplify setting and getting values.
Here's a C/JavaScript example illustrating memory interaction:
<code>( func $add(param $a i32) (param $b i32) (result i32) local.get $a local.get $b i32.add )</code>
<code class="language-javascript">const memory = new WebAssembly.Memory({ initial: 10, maximum: 100 });</code>
Remember to deallocate memory using _free
to prevent leaks. Modules can also define their own memory.
WebAssembly tables are separate memory segments storing function references, enabling dynamic function calls. This allows calling functions at runtime without prior knowledge of their names, using indices instead. This is crucial for scenarios like loading game plugins with unknown functions.
This overview covers WebAssembly's core components. For in-depth exploration, check out these resources:
Next, we'll build some practical projects!
The above is the detailed content of Components of WebAssembly. For more information, please follow other related articles on the PHP Chinese website!