Using exported globals
A WASM module can export entities, like functions, memories, globals and tables. This example illustrates how to use exported globals.
In this example we'll be using a simple WASM module which exports some globals.
Globals are probably the simplest entity we'll encounter in WASM modules but there is still some interesting things to talk about. For example, globals come in two flavors:
Immutable globals (
const)Mutable globals (
var)
We will cover both in this example.
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:
cargo new exports-global
cd exports-globalThis should generate two important files for us, Cargo.toml and src/main.rs. The Cargo.toml is a file that describes your project and its dependencies. The src/main.rs is the entry point for your project, and contains the fn main() { .. } that is run when the project is executed.
We then modify the Cargo.toml to add the Wasmer dependencies as shown below:
[package]
name = "exports-global"
version = "0.1.0"
authors = ["The Wasmer Engineering Team <engineering@wasmer.io>"]
edition = "2018"
[dependencies]
# The Wasmer API
wasmer = "1.0.0-alpha5"mkdir wasmer-example-imports-exports
cd wasmer-example-imports-exports
go mod init github.com/$USER/wasmer-example-imports-exportsLet's create a simple Makefile:
Now that we have everything set up, let's go ahead and try it out!
Querying types information
The first interesting thing to do is to query their type information in order to know if they are mutable or not. Our module exports two globals, one and some. Which one is mutable and which one is not?
Getting globals values
The global API is straightforward: it provides a dedicated method to get the value of a given global. Look how easy it is:
Setting globals
As we said before, globals come in two flavor. Immutable globals, for which we can only set a value once and mutable ones.
First we'll try to set the value of a immutable global and see what happens:
As you can see here, trying to set a value on a immutable global will always lead to an error.
Now let's see how to correctly set a value on a mutable global:
Running
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:
You should be able to run it using the go run main.go command. The output should look like this:
You should be able to run it using the make clean exports-global && ./exports-global command. The output should look like this:
Last updated
Was this helpful?