Files
wazero/example_test.go
Crypt Keeper 45ff2fe12f Propagates context to all api interface methods that aren't constant (#502)
This prepares for exposing operations like Memory.Grow while keeping the
ability to trace what did that, by adding a `context.Context` initial
parameter. This adds this to all API methods that mutate or return
mutated data.

Before, we made a change to trace functions and general lifecycle
commands, but we missed this part. Ex. We track functions, but can't
track what closed the module, changed memory or a mutable constant.
Changing to do this now is not only more consistent, but helps us
optimize at least the interpreter to help users identify otherwise
opaque code that can cause harm. This is critical before we add more
functions that can cause harm, such as Memory.Grow.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-25 08:13:18 +08:00

48 lines
1.1 KiB
Go

package wazero
import (
"context"
_ "embed"
"fmt"
"log"
)
// This is an example of how to use WebAssembly via adding two numbers.
//
// See https://github.com/tetratelabs/wazero/tree/main/examples for more examples.
func Example() {
// Choose the context to use for function calls.
ctx := context.Background()
// Create a new WebAssembly Runtime.
r := NewRuntime()
// Add a module to the runtime named "wasm/math" which exports one function "add", implemented in WebAssembly.
mod, err := r.InstantiateModuleFromCode(ctx, []byte(`(module $wasm/math
(func $add (param i32 i32) (result i32)
local.get 0
local.get 1
i32.add
)
(export "add" (func $add))
)`))
if err != nil {
log.Fatal(err)
}
defer mod.Close(ctx)
// Get a function that can be reused until its module is closed:
add := mod.ExportedFunction("add")
x, y := uint64(1), uint64(2)
results, err := add.Call(ctx, x, y)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %d + %d = %d\n", mod.Name(), x, y, results[0])
// Output:
// wasm/math: 1 + 2 = 3
}