forked from tetratelabs/wazero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add.go
70 lines (58 loc) · 1.68 KB
/
add.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"context"
_ "embed"
"fmt"
"log"
"os"
"strconv"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
)
// addWasm was generated by the following:
//
// cd testdata; tinygo build -o add.wasm -target=wasi add.go
//
//go:embed testdata/add.wasm
var addWasm []byte
// main is an example of how to extend a Go application with an addition
// function defined in WebAssembly.
//
// Since addWasm was compiled with TinyGo's `wasi` target, we need to configure
// WASI host imports.
func main() {
// Choose the context to use for function calls.
ctx := context.Background()
// Create a new WebAssembly Runtime.
r := wazero.NewRuntime(ctx)
defer r.Close(ctx) // This closes everything this Runtime created.
// Instantiate WASI, which implements host functions needed for TinyGo to
// implement `panic`.
wasi_snapshot_preview1.MustInstantiate(ctx, r)
// Instantiate the guest Wasm into the same runtime. It exports the `add`
// function, implemented in WebAssembly.
mod, err := r.InstantiateModuleFromBinary(ctx, addWasm)
if err != nil {
log.Panicln(err)
}
// Read two args to add.
x, y := readTwoArgs()
// Call the `add` function and print the results to the console.
add := mod.ExportedFunction("add")
results, err := add.Call(ctx, x, y)
if err != nil {
log.Panicln(err)
}
fmt.Printf("%d + %d = %d\n", x, y, results[0])
}
func readTwoArgs() (uint64, uint64) {
x, err := strconv.ParseUint(os.Args[1], 10, 64)
if err != nil {
log.Panicf("invalid arg %v: %v", os.Args[1], err)
}
y, err := strconv.ParseUint(os.Args[2], 10, 64)
if err != nil {
log.Panicf("invalid arg %v: %v", os.Args[2], err)
}
return x, y
}