github.com/tetratelabs/wazero@v1.7.3-0.20240513003603-48f702e154b5/example_test.go (about)

     1  package wazero_test
     2  
     3  import (
     4  	"context"
     5  	_ "embed"
     6  	"fmt"
     7  	"log"
     8  
     9  	"github.com/tetratelabs/wazero"
    10  	"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
    11  )
    12  
    13  // addWasm was generated by the following:
    14  //
    15  //	cd examples/basic/testdata; tinygo build -o add.wasm -target=wasi add.go
    16  //
    17  //go:embed examples/basic/testdata/add.wasm
    18  var addWasm []byte
    19  
    20  // This is an example of how to extend a Go application with an addition
    21  // function defined in WebAssembly.
    22  //
    23  // Since addWasm was compiled with TinyGo's `wasi` target, we need to configure
    24  // WASI host imports.
    25  //
    26  // A complete project that does the same as this is available here:
    27  // https://github.com/tetratelabs/wazero/tree/main/examples/basic
    28  func Example() {
    29  	// Choose the context to use for function calls.
    30  	ctx := context.Background()
    31  
    32  	// Create a new WebAssembly Runtime.
    33  	r := wazero.NewRuntime(ctx)
    34  	defer r.Close(ctx) // This closes everything this Runtime created.
    35  
    36  	// Instantiate WASI, which implements host functions needed for TinyGo to
    37  	// implement `panic`.
    38  	wasi_snapshot_preview1.MustInstantiate(ctx, r)
    39  
    40  	// Instantiate the guest Wasm into the same runtime. It exports the `add`
    41  	// function, implemented in WebAssembly.
    42  	mod, err := r.Instantiate(ctx, addWasm)
    43  	if err != nil {
    44  		log.Panicln(err)
    45  	}
    46  
    47  	// Call the `add` function and print the results to the console.
    48  	x, y := uint64(1), uint64(2)
    49  	results, err := mod.ExportedFunction("add").Call(ctx, x, y)
    50  	if err != nil {
    51  		log.Panicln(err)
    52  	}
    53  
    54  	fmt.Printf("%d + %d = %d\n", x, y, results[0])
    55  
    56  	// Output:
    57  	// 1 + 2 = 3
    58  }