github.com/wasilibs/wazerox@v0.0.0-20240124024944-4923be63ab5f/imports/emscripten/emscripten_example_test.go (about) 1 package emscripten_test 2 3 import ( 4 "context" 5 _ "embed" 6 7 wazero "github.com/wasilibs/wazerox" 8 "github.com/wasilibs/wazerox/imports/emscripten" 9 "github.com/wasilibs/wazerox/imports/wasi_snapshot_preview1" 10 ) 11 12 //go:embed testdata/invoke.wasm 13 var invokeWasm []byte 14 15 // This shows how to instantiate Emscripten function imports. 16 func Example_instantiateForModule() { 17 ctx := context.Background() 18 19 r := wazero.NewRuntime(ctx) 20 defer r.Close(ctx) // This closes everything this Runtime created. 21 22 // Add WASI which is typically required when using Emscripten. 23 wasi_snapshot_preview1.MustInstantiate(ctx, r) 24 25 // Compile the WASM so wazero can handle dynamically generated imports. 26 compiled, err := r.CompileModule(ctx, invokeWasm) 27 if err != nil { 28 panic(err) 29 } 30 31 envCloser, err := emscripten.InstantiateForModule(ctx, r, compiled) 32 if err != nil { 33 panic(err) 34 } 35 defer envCloser.Close(ctx) // This closes the env module. 36 37 // Output: 38 } 39 40 // This shows how to instantiate Emscripten function imports when you also need 41 // other functions in the "env" module. 42 func Example_functionExporter() { 43 ctx := context.Background() 44 45 r := wazero.NewRuntime(ctx) 46 defer r.Close(ctx) // This closes everything this Runtime created. 47 48 // Add WASI which is typically required when using Emscripten. 49 wasi_snapshot_preview1.MustInstantiate(ctx, r) 50 51 // Compile the WASM so wazero can handle dynamically generated imports. 52 compiled, err := r.CompileModule(ctx, invokeWasm) 53 if err != nil { 54 panic(err) 55 } 56 exporter, err := emscripten.NewFunctionExporterForModule(compiled) 57 if err != nil { 58 panic(err) 59 } 60 // Next, construct your own module builder for "env" with any functions 61 // you need. 62 envBuilder := r.NewHostModuleBuilder("env"). 63 NewFunctionBuilder(). 64 WithFunc(func() uint32 { return 1 }). 65 Export("get_int") 66 67 // Now, add Emscripten special function imports into it. 68 exporter.ExportFunctions(envBuilder) 69 // Output: 70 }