πŸ’Ύ
Interacting with memory
This example illustrates the basics of the basics of interacting with Wasm module memory.
A Wasm module can export its memory. With Wasmer you'll be able to interact with this memory.
In this example we'll illustrate the basics of interacting with the module memory:
    How to query information about the memory;
    How to load read from the memory;
    How to write to the memory.
There are mainly two ways of interacting with the memory, either through exported function or by calling the memory API directly. It really depends on how the memory is exported.
First we are going to want to initialize a new project. To do this we can navigate to our project folder, or create one. In this example, we will create a new project. Lets create it and navigate to it:
Rust
Go
C/C++
The final Rust code for this example can be found on Github: memory.rs.
Please take a look at the setup steps for Rust.
1
cargo new memory
2
cd memory
Copied!
We have to modify Cargo.toml to add the Wasmer dependencies as shown below:
1
[dependencies]
2
# The Wasmer API
3
wasmer = "2.0"
Copied!
The final Go code for this example can be found on Github: memory.go.
Please take a look at the setup steps for Go.
1
mkdir wasmer-example-memory
2
cd wasmer-example-memory
3
go mod init github.com/$USER/wasmer-example-memory
Copied!
The final C code for this example can be found on Github: memory.c.
Please take a look at the setup steps for C/C++.
1
mkdir wasmer-example-memory
2
cd wasmer-example-memory
3
vim Makefile
Copied!
Let's create a simple Makefile:
1
CFLAGS = -g -I$(shell $(WASMER_DIR)/bin/wasmer config --includedir)
2
LDFLAGS = -Wl,-rpath,$(shell $(WASMER_DIR)/bin/wasmer config --libdir)
3
LDLIBS = $(shell $(WASMER_DIR)/bin/wasmer config --libs)
4
​
5
.SILENT: memory memory.o
6
memory: memory.o
7
​
8
.PHONY: clean
9
.SILENT: clean
10
clean:
11
rm -f memory.o memory
Copied!
Now that we have everything set up, let's go ahead and try it out!

Querying memory information

The first interesting thing to do is to query information about the memory. To do that we must either have access to the memory (i.e it has to be exported) or we must have access to an exported function which is able to give us this information.
One important thing to note: the size of the memory can be expressed as a number of pages or a number of bytes.
Each page of memory is 64 KiB in size.
Rust
Go
C/C++
1
let mem_size: NativeFunc<(), i32> = instance
2
.exports
3
.get_native_function("mem_size")?;
4
let memory = instance.exports.get_memory("memory")?;
5
​
6
assert_eq!(memory.size(), Pages::from(1));
7
assert_eq!(memory.size().bytes(), Bytes::from(65536 as usize));
8
assert_eq!(memory.data_size(), 65536);
9
​
10
let result = mem_size.call()?;
11
assert_eq!(Pages::from(result as u32), memory.size());
Copied!
1
memSize, err := instance.Exports.GetFunction("mem_size")
2
​
3
if err != nil {
4
panic(fmt.Sprintln("Failed to retrieve the `mem_size` function:", err))
5
}
6
​
7
memory, err := instance.Exports.GetMemory("memory")
8
​
9
if err != nil {
10
panic(fmt.Sprintln("Failed to get the `memory` memory:", err))
11
}
12
​
13
size := memory.Size()
14
fmt.Println("Memory size (pages):", size)
15
fmt.Println("Memory size (pages as bytes):", size.ToBytes())
16
fmt.Println("Memory size (bytes):", memory.DataSize())
17
​
18
result, err := memSize()
19
​
20
if err != nil {
21
panic(fmt.Sprintln("Failed to call the `mem_size` function:", err))
22
}
23
​
24
fmt.Println("Memory size (pages):", result)
Copied!
1
wasm_memory_pages_t pages = wasm_memory_size(memory);
2
size_t data_size = wasm_memory_data_size(memory);
3
​
4
printf("Memory size (pages): %d\n", pages);
5
printf("Memory size (bytes): %d\n", (int) data_size);
Copied!
Now that we know the size of our memory it's time to see how we can change this.

Growing the memory

A memory can be grown to allow storing more things into it. This is easily done through
Rust
Go
C/C++
1
memory.grow(2)?;
2
assert_eq!(memory.size(), Pages::from(3));
3
assert_eq!(memory.data_size(), 65536 * 3);
Copied!
1
memory.Grow(2)
2
fmt.Println("New memory size (pages):", memory.Size())
Copied!
1
if (!wasm_memory_grow(memory, 2)) {
2
printf("> Error growing memory!\n");
3
​
4
return 1;
5
}
6
​
7
wasm_memory_pages_t new_pages = wasm_memory_size(memory);
8
printf("New memory size (pages): %d\n", new_pages);
Copied!
To grow a memory you have to call the dedicated method and provide the number of pages, called the delta, you want to add to the memory.

Reading from and writing to the memory

Now that we know how to query and adjust the size of the memory, let's see how we can write to it or read from it.
We'll only focus on how to do this using exported functions, the goal is to show how to work with memory addresses.
Let's start by using absolute memory addresses to write and read a value.
Rust
Go
C/C++
1
let get_at: NativeFunc<i32, i32> = instance
2
.exports
3
.get_native_function("get_at")?;
4
let set_at: NativeFunc<(i32, i32), ()> = instance
5
.exports
6
.get_native_function("set_at")?;
7
​
8
let mem_addr = 0x2220;
9
let val = 0xFEFEFFE;
10
​
11
set_at.call(mem_addr, val)?;
12
​
13
let result = get_at.call(mem_addr)?;
14
println!("Value at {:#x?}: {:?}", mem_addr, result);
Copied!
1
getAt, err := instance.Exports.GetFunction("get_at")
2
​
3
if err != nil {
4
panic(fmt.Sprintln("Failed to retrieve the `get_at` function:", err))
5
}
6
​
7
setAt, err := instance.Exports.GetFunction("set_at")
8
​
9
if err != nil {
10
panic(fmt.Sprintln("Failed to retrieve the `set_at` function:", err))
11
}
12
​
13
memAddr := 0x2220
14
val := 0xFEFEFFE
15
_, err = setAt(memAddr, val)
16
​
17
if err != nil {
18
panic(fmt.Sprintln("Failed to call the `set_at` function:", err))
19
}
20
​
21
result, err = getAt(memAddr)
22
​
23
if err != nil {
24
panic(fmt.Sprintln("Failed to call the `get_at` function:", err))
25
}
26
​
27
fmt.Printf("Value at 0x%x: %d\n", memAddr, result)
Copied!
1
wasm_func_t* get_at = wasm_extern_as_func(exports.data[0]);
2
wasm_func_t* set_at = wasm_extern_as_func(exports.data[1]);
3
​
4
int mem_addr = 0x2220;
5
int val = 0xFEFEFFE;
6
​
7
wasm_val_t set_at_args_val[2] = { WASM_I32_VAL(mem_addr), WASM_I32_VAL(val) };
8
wasm_val_vec_t set_at_args = WASM_ARRAY_VEC(set_at_args_val);
9
wasm_val_vec_t set_at_results = WASM_EMPTY_VEC;
10
wasm_func_call(set_at, &set_at_args, &set_at_results);
11
​
12
wasm_val_t get_at_args_val[1] = { WASM_I32_VAL(mem_addr) };
13
wasm_val_vec_t get_at_args = WASM_ARRAY_VEC(get_at_args_val);
14
wasm_val_t get_at_results_val[1] = { WASM_INIT_VAL };
15
wasm_val_vec_t get_at_results = WASM_ARRAY_VEC(get_at_results_val);
16
wasm_func_call(get_at, &get_at_args, &get_at_results);
17
​
18
printf("Value at 0x%04x: %d\n", mem_addr, get_at_results_val[0].of.i32);
Copied!
Now assume we want to write a value at the end of the second memory page and the read it. Let's see how we can do that:
Rust
Go
1
let page_size = 0x1_0000;
2
let mem_addr = (page_size * 2) - mem::size_of_val(&val) as i32;
3
let val = 0xFEA09;
4
set_at.call(mem_addr, val)?;
5
​
6
let result = get_at.call(mem_addr)?;
7
println!("Value at {:#x?}: {:?}", mem_addr, result);
Copied!
1
pageSize := 0x1_0000
2
memAddr = (pageSize * 2) - int(unsafe.Sizeof(val))
3
val = 0xFEA09
4
_, err = setAt(memAddr, val)
5
​
6
if err != nil {
7
panic(fmt.Sprintln("Failed to call the `set_at` function:", err))
8
}
9
​
10
result, err = getAt(memAddr)
11
​
12
if err != nil {
13
panic(fmt.Sprintln("Failed to call the `get_at` function:", err))
14
}
15
​
16
fmt.Printf("Value at 0x%x: %d\n", memAddr, result)
Copied!
As you can see here we can use the size of a page and the size of the value we want to write to compute an address and write to it.
Keep in mind that memory address can be any number you want as long as it is valid regarding the memory size.
In the previous examples, we used hexadecimal notation but you are free to use decimal notation if needed.
It enough for now: we only covered how to interact with the memory through exported functions. If you want to know more, see the following example:

Running

We now have everything we need to run the Wasm module, let's do it!
Rust
Go
C/C++
You should be able to run it using the cargo run command. The output should look like this:
1
Compiling module...
2
Instantiating module...
3
Querying memory size...
4
Memory size: 1
5
Growing memory...
6
Value at 0x2220: 267382782
7
Value at 0x1fffc: 1042953
Copied!
If you want to run the examples from the Wasmer repository codebase directly, you can also do:
1
git clone https://github.com/wasmerio/wasmer.git
2
cd wasmer
3
cargo run --example memory --release --features "cranelift"
Copied!
You should be able to run it using the go run main.go command. The output should look like this:
1
Compiling module...
2
Instantiating module...
3
Querying memory size...
4
Memory size (pages): 1
5
Memory size (pages as bytes): 65536
6
Memory size (bytes): 65536
7
Memory size (pages): 1
8
Growing memory...
9
New memory size (pages): 3
10
Value at 0x2220: 267382782
11
Value at 0x1fff8: 1042953
Copied!
If you want to run the examples from the Wasmer repository codebase directly, you can also do:
1
git clone https://github.com/wasmerio/wasmer-go.git
2
cd wasmer-go
3
go test examples/example_memory_test.go
Copied!
You should be able to run it using the make clean memory && ./memory command. The output should look like this:
1
Creating the store...
2
Compiling module...
3
Creating imports...
4
Instantiating module...
5
Retrieving exports...
6
Querying memory size...
7
Memory size (pages): 1
8
Memory size (bytes): 65536
9
Growing memory...
10
New memory size (pages): 3
11
Value at 0x2220: 267382782
Copied!
If you want to run the examples from the Wasmer repository codebase directly, you can also do:
1
git clone https://github.com/wasmerio/wasmer.git
2
cd wasmer/lib/c-api/examples/memory
3
make clean memory
4
./memory
Copied!
Last modified 4mo ago