wa-lang.org/wazero@v1.0.2/examples/basic/add.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	_ "embed"
     6  	"fmt"
     7  	"log"
     8  	"os"
     9  	"strconv"
    10  
    11  	"wa-lang.org/wazero"
    12  	"wa-lang.org/wazero/imports/wasi_snapshot_preview1"
    13  )
    14  
    15  // addWasm was generated by the following:
    16  //
    17  //	cd testdata; tinygo build -o add.wasm -target=wasi add.go
    18  //
    19  //go:embed testdata/add.wasm
    20  var addWasm []byte
    21  
    22  // main is an example of how to extend a Go application with an addition
    23  // function defined in WebAssembly.
    24  //
    25  // Since addWasm was compiled with TinyGo's `wasi` target, we need to configure
    26  // WASI host imports.
    27  func main() {
    28  	// Choose the context to use for function calls.
    29  	ctx := context.Background()
    30  
    31  	// Create a new WebAssembly Runtime.
    32  	r := wazero.NewRuntime(ctx)
    33  	defer r.Close(ctx) // This closes everything this Runtime created.
    34  
    35  	// Instantiate WASI, which implements host functions needed for TinyGo to
    36  	// implement `panic`.
    37  	wasi_snapshot_preview1.MustInstantiate(ctx, r)
    38  
    39  	// Instantiate the guest Wasm into the same runtime. It exports the `add`
    40  	// function, implemented in WebAssembly.
    41  	mod, err := r.InstantiateModuleFromBinary(ctx, addWasm)
    42  	if err != nil {
    43  		log.Panicln(err)
    44  	}
    45  
    46  	// Read two args to add.
    47  	x, y := readTwoArgs()
    48  
    49  	// Call the `add` function and print the results to the console.
    50  	add := mod.ExportedFunction("add")
    51  	results, err := add.Call(ctx, x, y)
    52  	if err != nil {
    53  		log.Panicln(err)
    54  	}
    55  
    56  	fmt.Printf("%d + %d = %d\n", x, y, results[0])
    57  }
    58  
    59  func readTwoArgs() (uint64, uint64) {
    60  	x, err := strconv.ParseUint(os.Args[1], 10, 64)
    61  	if err != nil {
    62  		log.Panicf("invalid arg %v: %v", os.Args[1], err)
    63  	}
    64  
    65  	y, err := strconv.ParseUint(os.Args[2], 10, 64)
    66  	if err != nil {
    67  		log.Panicf("invalid arg %v: %v", os.Args[2], err)
    68  	}
    69  	return x, y
    70  }