WebAssembly modules act as the templating backbone for WebAssembly programs. In a WebAssembly module, you will find three main components: the function index space, the table index space, and the memory index space. Each module comprises a sequence of definitions, with each being either a function, a table, a memory, or a global. Global definitions include constants in WebAssembly.
The most significant aspect of the module in WebAssembly is that once it has been compiled, it can be reused in any other place where you want to use the same functionality and logic. You can think of it as encapsulating a set of functions that embody a 'higher-level' version of a microservice in web development terms.
For instance, consider a simple module that contains a function that adds two integers. In our C++ version, it would look something like this:
1// An example of a simple module
2// This would be represented as wasm binary in a actual WebAssembly application
3// module $moduleName
4
5// A function that adds two integers
6// func $add (param $a i32) (param $b i32) (result i32)
7// (i32.add (get_local $a) (get_local $b))
8int add(int a, int b) {
9 return a + b;
10}
11
12int a = 42;
13int b = 28;
14
15cout << "The sum of a and b is: " << add(a, b) << endl;
Although this example is in C++, the equivalent WebAssembly binary module would have the same structure. Given that our audience is very experienced in web development, the analogy between WebAssembly modules and microservices or JavaScript modules might help to conceptualize the principle.
xxxxxxxxxx
using namespace std;
int main() {
// An example of a simple module
// This would be represented as wasm binary in a actual WebAssembly application
// module $moduleName
// A function that adds two integers
// func $add (param $a i32) (param $b i32) (result i32)
// (i32.add (get_local $a) (get_local $b))
int add(int a, int b) {
return a + b;
}
int a = 42;
int b = 28;
cout << "The sum of a and b is: " << add(a, b) << endl;
return 0;
}