github.com/tetratelabs/wazero@v1.7.3-0.20240513003603-48f702e154b5/imports/assemblyscript/example/assemblyscript.go (about) 1 package main 2 3 import ( 4 "context" 5 _ "embed" 6 "fmt" 7 "log" 8 "os" 9 "strconv" 10 11 "github.com/tetratelabs/wazero" 12 "github.com/tetratelabs/wazero/imports/assemblyscript" 13 ) 14 15 // asWasm compiled using `npm install && npm run build` 16 // 17 //go:embed testdata/index.wasm 18 var asWasm []byte 19 20 // main shows how to interact with a WebAssembly function that was compiled 21 // from AssemblyScript 22 // 23 // See README.md for a full description. 24 func main() { 25 // Choose the context to use for function calls. 26 ctx := context.Background() 27 28 // Create a new WebAssembly Runtime. 29 r := wazero.NewRuntime(ctx) 30 defer r.Close(ctx) // This closes everything this Runtime created. 31 32 // Instantiate a module implementing functions used by AssemblyScript. 33 // Thrown errors will be logged to os.Stderr 34 _, err := assemblyscript.Instantiate(ctx, r) 35 if err != nil { 36 log.Panicln(err) 37 } 38 39 // Instantiate a WebAssembly module that imports the "abort" and "trace" 40 // functions defined by assemblyscript.Instantiate and exports functions 41 // we'll use in this example. 42 mod, err := r.InstantiateWithConfig(ctx, asWasm, 43 // Override the default module config that discards stdout and stderr. 44 wazero.NewModuleConfig().WithStdout(os.Stdout).WithStderr(os.Stderr)) 45 if err != nil { 46 log.Panicln(err) 47 } 48 49 // Get references to WebAssembly functions we'll use in this example. 50 helloWorld := mod.ExportedFunction("hello_world") 51 goodbyeWorld := mod.ExportedFunction("goodbye_world") 52 53 // Let's use the argument to this main function in Wasm. 54 numStr := os.Args[1] 55 num, err := strconv.Atoi(numStr) 56 if err != nil { 57 log.Panicln(err) 58 } 59 60 // Call hello_world, which returns the input value incremented by 3. 61 // While this calls trace(), our configuration didn't enable it. 62 results, err := helloWorld.Call(ctx, uint64(num)) 63 if err != nil { 64 log.Panicln(err) 65 } 66 fmt.Printf("hello_world returned: %v", results[0]) 67 68 // Call goodbye_world, which aborts with an error. 69 // assemblyscript.Instantiate was configured above to abort to stderr. 70 if _, err = goodbyeWorld.Call(ctx); err == nil { 71 log.Panicln("goodbye_world did not fail") 72 } 73 }