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

Function ExampleModule_serialize

example_test.go:440–503  ·  view source on GitHub ↗

Small example of how to serialize a compiled wasm module, and then instantiate it from the compilation artifacts.

()

Source from the content-addressed store, hash-verified

438// Small example of how to serialize a compiled wasm module, and then
439// instantiate it from the compilation artifacts.
440func ExampleModule_serialize() {
441 // Configure the initial compilation environment.
442 engine := wasmtime.NewEngine()
443
444 // Compile the wasm module into an in-memory instance of a `Module`.
445 wasm, err := wasmtime.Wat2Wasm(`
446 (module
447 (func $hello (import "" "hello"))
448 (func (export "run") (call $hello))
449 )
450 `)
451 if err != nil {
452 log.Fatal(err)
453 }
454 module, err := wasmtime.NewModule(engine, wasm)
455 if err != nil {
456 log.Fatal(err)
457 }
458 bytes, err := module.Serialize()
459 if err != nil {
460 log.Fatal(err)
461 }
462
463 // Configure the initial compilation environment.
464 store := wasmtime.NewStore(wasmtime.NewEngine())
465
466 // Deserialize the compiled module.
467 module, err = wasmtime.NewModuleDeserialize(store.Engine, bytes)
468 if err != nil {
469 log.Fatal(err)
470 }
471
472 // Here we handle the imports of the module, which in this case is our
473 // `helloFunc` callback.
474 helloFunc := wasmtime.WrapFunc(store, func() {
475 fmt.Println("Calling back...")
476 fmt.Println("> Hello World!")
477 })
478
479 // Once we've got that all set up we can then move to the instantiation
480 // phase, pairing together a compiled module as well as a set of imports.
481 // Note that this is where the wasm `start` function, if any, would run.
482 instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{helloFunc})
483 if err != nil {
484 log.Fatal(err)
485 }
486
487 // Next we poke around a bit to extract the `run` function from the module.
488 run := instance.GetFunc(store, "run")
489 if run == nil {
490 log.Fatal("Failed to find function export `run`")
491 }
492
493 // And last but not least we can call it!
494 fmt.Println("Calling export...")
495 _, err = run.Call(store)
496 if err != nil {
497 log.Fatal(err)

Callers

nothing calls this directly

Calls 3

SerializeMethod · 0.95
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…