Files
wazero/examples/basic/add.go
Crypt Keeper 92ba4929e5 Drops support for the WebAssembly text format (#614)
This drops the text format (%.wat) and renames
InstantiateModuleFromCode to InstantiateModuleFromBinary as it is no
longer ambiguous.

We decided to stop supporting the text format as it isn't typically used
in production, yet costs a lot of work to develop. Given the resources
available and the increased work added with WebAssembly 2.0 and soon
WASI 2, we can't afford to spend the time on it.

The old parser is used only internally and will eventually be moved to
its own repository named watzero, possibly towards archival.

See #59

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-06-01 19:01:43 +08:00

71 lines
1.7 KiB
Go

package main
import (
"context"
_ "embed"
"fmt"
"log"
"os"
"strconv"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
)
// 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)
}
// Add a module to the runtime named "host/math" which exports one function "add", implemented in Go.
host, err := r.NewModuleBuilder("host/math").
ExportFunction("add", func(v1, v2 uint32) uint32 {
return v1 + v2
}).Instantiate(ctx, r)
if err != nil {
log.Panicln(err)
}
// Read two args to add.
x, y := readTwoArgs()
// Call the same function in both modules and print the results to the console.
for _, mod := range []api.Module{wasm, host} {
add := mod.ExportedFunction("add")
results, err := add.Call(ctx, x, y)
if err != nil {
log.Panicln(err)
}
fmt.Printf("%s: %d + %d = %d\n", mod.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
}