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

Function Example_storedata

example_test.go:776–842  ·  view source on GitHub ↗

An example of using [NewStoreWithData] to associate arbitrary data with a [Store], accessible in a callback function via [Caller.Data]

()

Source from the content-addressed store, hash-verified

774// An example of using [NewStoreWithData] to associate arbitrary data with a [Store], accessible in
775// a callback function via [Caller.Data]
776func Example_storedata() {
777 // First, create an engine. This'll hold our linker and compiled module.
778 engine := wasmtime.NewEngine()
779
780 // Create our wasm module in text format (wat)
781 wasm, err := wasmtime.Wat2Wasm(`
782 (module
783 (import "" "hello" (func $hello (param i32)))
784 (import "session" "get_request_id" (func $get_req_id (result i32)))
785 (func (export "run")
786 (call $hello (call $get_req_id))
787 )
788 )
789 `)
790 if err != nil {
791 log.Fatal(err)
792 }
793
794 // Once we have our binary `wasm` we can compile that into a `*Module`
795 // which represents compiled JIT code.
796 module, err := wasmtime.NewModule(engine, wasm)
797 if err != nil {
798 log.Fatal(err)
799 }
800
801 // Our wasm module imports two functions, which we're going to implement on the linker.
802 linker := wasmtime.NewLinker(engine)
803
804 // Implement host function session::get_request_id
805 linker.FuncWrap("session", "get_request_id", func(c *wasmtime.Caller) int32 {
806 data := c.Data().(*sessionData)
807 return data.request_id
808 })
809
810 // Implement host function ::hello
811 linker.FuncWrap("", "hello", func(arg0 int32) {
812 fmt.Printf("Hello request %d\n", arg0)
813 })
814
815 // Now, we're going to create 5 instances of our module using this linker, and each instance
816 // will have its own request id.
817 for i := 0; i < 5; i++ {
818 store := wasmtime.NewStoreWithData(engine, &sessionData{
819 request_id: int32(i),
820 })
821
822 instance, err := linker.Instantiate(store, module)
823 if err != nil {
824 log.Fatal(err)
825 }
826
827 // After we've instantiated we can lookup our `run` function and call
828 // it.
829 run := instance.GetFunc(store, "run")
830 _, err = run.Call(store)
831 if err != nil {
832 log.Fatal(err)
833 }

Callers

nothing calls this directly

Calls 5

FuncWrapMethod · 0.95
InstantiateMethod · 0.95
GetFuncMethod · 0.80
CallMethod · 0.80
DataMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…