forked from tetratelabs/wazero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
47 lines (39 loc) · 1.05 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
}