Files
wazero/examples/basic/add.go
Takeshi Yoneda 02c23d55db Disallow direct call of host functions (#723)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-07-30 09:33:20 +08:00

61 lines
1.3 KiB
Go

package main
import (
"context"
_ "embed"
"fmt"
"log"
"os"
"strconv"
"github.com/tetratelabs/wazero"
)
// addWasm was generated by the following:
//
// cd testdata; wat2wasm --debug-names add.wat
//
//go:embed testdata/add.wasm
var addWasm []byte
// main implements a basic function in both Go and WebAssembly.
func main() {
// Choose the context to use for function calls.
ctx := context.Background()
// Create a new WebAssembly Runtime.
r := wazero.NewRuntime()
defer r.Close(ctx) // This closes everything this Runtime created.
// Add a module to the runtime named "wasm/math" which exports one function "add", implemented in WebAssembly.
wasm, err := r.InstantiateModuleFromBinary(ctx, addWasm)
if err != nil {
log.Panicln(err)
}
// Read two args to add.
x, y := readTwoArgs()
// Call the `add` function in the module and print the results to the console.
add := wasm.ExportedFunction("add")
results, err := add.Call(ctx, x, y)
if err != nil {
log.Panicln(err)
}
fmt.Printf("%s: %d + %d = %d\n", wasm.Name(), 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
}