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

Function ExampleMemory

example_test.go:312–436  ·  view source on GitHub ↗

An example of working with the Memory type to read/write wasm memory.

()

Source from the content-addressed store, hash-verified

310
311// An example of working with the Memory type to read/write wasm memory.
312func ExampleMemory() {
313 // Create our `Store` context and then compile a module and create an
314 // instance from the compiled module all in one go.
315 store := wasmtime.NewStore(wasmtime.NewEngine())
316 wasm, err := wasmtime.Wat2Wasm(`
317 (module
318 (memory (export "memory") 2 3)
319
320 (func (export "size") (result i32) (memory.size))
321 (func (export "load") (param i32) (result i32)
322 (i32.load8_s (local.get 0))
323 )
324 (func (export "store") (param i32 i32)
325 (i32.store8 (local.get 0) (local.get 1))
326 )
327
328 (data (i32.const 0x1000) "\01\02\03\04")
329 )
330 `)
331 if err != nil {
332 log.Fatal(err)
333 }
334 module, err := wasmtime.NewModule(store.Engine, wasm)
335 if err != nil {
336 log.Fatal(err)
337 }
338 instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{})
339 if err != nil {
340 log.Fatal(err)
341 }
342
343 // Load up our exports from the instance
344 memory := instance.GetExport(store, "memory").Memory()
345 sizeFn := instance.GetFunc(store, "size")
346 loadFn := instance.GetFunc(store, "load")
347 storeFn := instance.GetFunc(store, "store")
348
349 // some helper functions we'll use below
350 call32 := func(f *wasmtime.Func, args ...interface{}) int32 {
351 ret, err := f.Call(store, args...)
352 if err != nil {
353 log.Fatal(err)
354 }
355 return ret.(int32)
356 }
357 call := func(f *wasmtime.Func, args ...interface{}) {
358 _, err := f.Call(store, args...)
359 if err != nil {
360 log.Fatal(err)
361 }
362 }
363 assertTraps := func(f *wasmtime.Func, args ...interface{}) {
364 _, err := f.Call(store, args...)
365 _, ok := err.(*wasmtime.Trap)
366 if !ok {
367 log.Fatal("expected a trap")
368 }
369 }

Callers

nothing calls this directly

Calls 10

GetExportMethod · 0.95
GetFuncMethod · 0.95
SizeMethod · 0.95
GrowMethod · 0.95
MemoryMethod · 0.80
CallMethod · 0.80
DataSizeMethod · 0.80
UnsafeDataMethod · 0.80
SizeMethod · 0.45
GrowMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…