wa-lang.org/wazero@v1.0.2/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 "wa-lang.org/wazero" 12 "wa-lang.org/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 // Compile the WebAssembly module using the default configuration. 40 code, err := r.CompileModule(ctx, asWasm) 41 if err != nil { 42 log.Panicln(err) 43 } 44 45 // Instantiate a WebAssembly module that imports the "abort" and "trace" 46 // functions defined by assemblyscript.Instantiate and exports functions 47 // we'll use in this example. 48 mod, err := r.InstantiateModule(ctx, code, wazero.NewModuleConfig(). 49 // Override the default module config that discards stdout and stderr. 50 WithStdout(os.Stdout).WithStderr(os.Stderr)) 51 if err != nil { 52 log.Panicln(err) 53 } 54 55 // Get references to WebAssembly functions we'll use in this example. 56 helloWorld := mod.ExportedFunction("hello_world") 57 goodbyeWorld := mod.ExportedFunction("goodbye_world") 58 59 // Let's use the argument to this main function in Wasm. 60 numStr := os.Args[1] 61 num, err := strconv.Atoi(numStr) 62 if err != nil { 63 log.Panicln(err) 64 } 65 66 // Call hello_world, which returns the input value incremented by 3. 67 // While this calls trace(), our configuration didn't enable it. 68 results, err := helloWorld.Call(ctx, uint64(num)) 69 if err != nil { 70 log.Panicln(err) 71 } 72 fmt.Printf("hello_world returned: %v", results[0]) 73 74 // Call goodbye_world, which aborts with an error. 75 // assemblyscript.Instantiate was configured above to abort to stderr. 76 if _, err = goodbyeWorld.Call(ctx); err == nil { 77 log.Panicln("goodbye_world did not fail") 78 } 79 }