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:
The final code for this example can be found on GitHub.
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.
let mem_size:NativeFunc<(), i32> = instance.exports.get_native_function("mem_size")?;let memory = instance.exports.get_memory("memory")?;assert_eq!(memory.size(), Pages::from(1));assert_eq!(memory.size().bytes(), Bytes::from(65536asusize));assert_eq!(memory.data_size(), 65536);let result = mem_size.call()?;assert_eq!(Pages::from(result asu32), memory.size());
memSize, err := instance.Exports.GetFunction("mem_size")if err !=nil {panic(fmt.Sprintln("Failed to retrieve the `mem_size` function:", err))}memory, err := instance.Exports.GetMemory("memory")if err !=nil {panic(fmt.Sprintln("Failed to get the `memory` memory:", err))}size := memory.Size()fmt.Println("Memory size (pages):", size)fmt.Println("Memory size (pages as bytes):", size.ToBytes())fmt.Println("Memory size (bytes):", memory.DataSize())result, err :=memSize()if err !=nil {panic(fmt.Sprintln("Failed to call the `mem_size` function:", err))}fmt.Println("Memory size (pages):", result)
We now have everything we need to run the Wasm module, let's do it!
You should be able to run it using the cargo run command. The output should look like this:
Compiling module...
Instantiating module...
Querying memory size...
Memory size: 1
Growing memory...
Value at 0x2220: 267382782
Value at 0x1fffc: 1042953
If you want to run the examples from the Wasmer repository codebase directly, you can also do: