use mlua::Lua; use std::error::Error; #[test] fn wasmer_examples_exports_memory() -> Result<(), Box> { let lua = Lua::new(); mlua_wasmer::preload(&lua)?; let script = r#" -- Let's declare the Wasm module with the text representation. local module_wat = [[ (module (memory (export "mem") 1) (global $offset i32 (i32.const 42)) (global $length (mut i32) (i32.const 13)) (func (export "load") (result i32 i32) global.get $offset global.get $length) (data (i32.const 42) "Hello, World!")) ]] -- Create a Store. local wasmer = require('wasmer') local store = wasmer.Store:default() -- Let's compile the Wasm module. print('Compiling module...') local module = wasmer.Module:new(store, module_wat) -- Create an empty import object. local import_object = wasmer.Imports:new() -- Let's instantiate the Wasm module. print('Instantiating module...') local instance = wasmer.Instance:new(store, module, import_object) local load = instance.exports:get_function('load') -- Here we go. The Wasm module exports a memory under 'mem'. Let's get it. local memory = instance.exports:get_memory('mem') -- Now that we have the exported memory, let's get some information about it. local memory_view = memory:view(store) print(string.format('Memory size (pages) %s', tostring(memory_view:size()))) print(string.format('Memory size (bytes) %d', memory_view:data_size())) -- Oh! Wait, before reading the contents, we need to know where to find what we are looking for. -- Fortunately, the Wasm module exports a `load` function -- which will tell us the offset and length of the string. local offset, length = load:call(store) print(string.format('String offset: %d', offset)) print(string.format('String length: %d', length)) -- We now know where to find our string, let's read it. -- We will get bytes out of the memory so we need to decode them into a string. local ptr = wasmer.WasmPtr_u8:new(offset) local str = ptr:read_utf8_string(memory_view, length) print(string.format('Memory contents: %s', str)) return str "#; let str: String = lua.load(script).eval()?; assert_eq!(str, "Hello, World!"); Ok(()) }