MCPcopy Create free account
hub / github.com/bytecodealliance/wasmtime-go / Example_hello

Function Example_hello

example_test.go:668–716  ·  view source on GitHub ↗

An example of instantiating a small wasm module which imports functionality from the host, then calling into wasm which calls back into the host.

()

Source from the content-addressed store, hash-verified

666// An example of instantiating a small wasm module which imports functionality
667// from the host, then calling into wasm which calls back into the host.
668func Example_hello() {
669 // Almost all operations in wasmtime require a contextual `store`
670 // argument to share, so create that first
671 store := wasmtime.NewStore(wasmtime.NewEngine())
672
673 // Compiling modules requires WebAssembly binary input, but the wasmtime
674 // package also supports converting the WebAssembly text format to the
675 // binary format.
676 wasm, err := wasmtime.Wat2Wasm(`
677 (module
678 (import "" "hello" (func $hello))
679 (func (export "run")
680 (call $hello)
681 )
682 )
683 `)
684 if err != nil {
685 log.Fatal(err)
686 }
687
688 // Once we have our binary `wasm` we can compile that into a `*Module`
689 // which represents compiled JIT code.
690 module, err := wasmtime.NewModule(store.Engine, wasm)
691 if err != nil {
692 log.Fatal(err)
693 }
694
695 // Our `hello.wat` file imports one item, so we create that function
696 // here.
697 item := wasmtime.WrapFunc(store, func() {
698 fmt.Println("Hello from Go!")
699 })
700
701 // Next up we instantiate a module which is where we link in all our
702 // imports. We've got one import so we pass that in here.
703 instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{item})
704 if err != nil {
705 log.Fatal(err)
706 }
707
708 // After we've instantiated we can lookup our `run` function and call
709 // it.
710 run := instance.GetFunc(store, "run")
711 _, err = run.Call(store)
712 if err != nil {
713 log.Fatal(err)
714 }
715 // Output: Hello from Go!
716}
717
718// An example of a wasm module which calculates the GCD of two numbers
719func Example_gcd() {

Callers

nothing calls this directly

Calls 2

GetFuncMethod · 0.95
CallMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…