### Basic Wasmer Python API Usage Source: https://wasmerio.github.io/wasmer-python/api/wasmer Demonstrates the fundamental steps of using the Wasmer Python API: creating a Store, compiling a WebAssembly module from WAT (WebAssembly Text format), instantiating the module, and executing an exported function. This example requires the 'wasmer' library to be installed. ```python from wasmer import Store, Module, Instance # Create a store, which holds the engine, the compiler etc. store = Store() # Let's assume we don't have WebAssembly bytes at hand. We will # write WebAssembly manually. module = Module( store, """ (module (type (func (param i32 i32) (result i32))) (func (type 0) local.get 0 local.get 1 i32.add) (export "sum" (func 0))) "") # Instantiates the module. instance = Instance(module) # Now, let's execute the `sum` function. assert instance.exports.sum(1, 2) == 3 ``` -------------------------------- ### Wasmer Python TypedArray Views Example Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Illustrates how to use typed array views (e.g., `Uint8Array`) in the Wasmer Python API to access and interpret data within WebAssembly memory. This example shows reading a null-terminated string from memory, starting from a given pointer. The code relies on importing `Store`, `Module`, `Instance`, and the specific array view class from the `wasmer` library. The example assumes a WASM module with exports named `string` and `memory`. ```python from wasmer import Store, Module, Instance, Uint8Array module = Module(Store(), open('tests/tests.wasm', 'rb').read()) instance = Instance(module) exports = instance.exports pointer = exports.string() memory = exports.memory.uint8_view(offset=pointer) nth = 0 string = '' while (0 != memory[nth]): string += chr(memory[nth]) nth += 1 assert string == 'Hello, World!' ``` -------------------------------- ### Instantiate WASI Module Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Sets up and instantiates a WebAssembly module that requires WASI support. This involves getting the WASI version, building a WASI environment, generating an import object, and then creating the Wasmer instance. ```python from wasmer import wasi, Store, Module, Instance store = Store() module = Module(store, open('tests/wasi.wasm', 'rb').read()) # Get the WASI version. wasi_version = wasi.get_version(module, strict=True) # Build a WASI environment for the imports. wasi_env = wasi.StateBuilder('test-program').argument('--foo').finalize() # Generate an `ImportObject` from the WASI environment. import_object = wasi_env.generate_import_object(store, wasi_version) # Now we are ready to instantiate the module. instance = Instance(module, import_object) # Here we go, let's start the program. instance.exports._start() ``` -------------------------------- ### Instantiating Wasm Module without Imports (Python) Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Shows how to create a WebAssembly `Instance` from a `Module` without any external dependencies. The example defines a simple Wasm module that exports a `sum` function. ```python from wasmer import Store, Module, Instance module = Module( Store(), """ (module (type (func (param i32 i32) (result i32))) (func (type 0) local.get 0 local.get 1 i32.add) (export "sum" (func 0))) """ ) instance = Instance(module) assert instance.exports.sum(1, 2) == 3 ``` -------------------------------- ### Define WebAssembly TableType using Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer This example shows how to define a `TableType` in Python, which describes a WebAssembly table. It illustrates how to specify the element type, minimum size, and optional maximum size of the table. ```python from wasmer import TableType, Type table_type = TableType(Type.I32, minimum=7, maximum=42) ``` -------------------------------- ### Convert WebAssembly Text to Binary Format in Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Provides an example of using the `wat2wasm` function from the `wasmer` library to convert WebAssembly text format (WAT) into its binary representation. This is useful for pre-compiling or handling WAT sources directly. ```python from wasmer import wat2wasm assert wat2wasm('(module)') == b'\x00asm\x01\x00\x00\x00' ``` -------------------------------- ### Instantiating Wasm Module with Imports (Python) Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Demonstrates creating a WebAssembly `Instance` with an `ImportObject`. This example defines a Wasm module that imports a `sum` function and exports an `add_one` function that utilizes the imported function. ```python from wasmer import Store, Module, Instance, Function from collections import defaultdict # Let's define the `sum` function! def sum(x: int, y: int) -> int: return x + y # Let's build a store, as usual. store = Store() # Let's compile the WebAssembly module. module = Module( store, """ (module (import "math" "sum" (func $sum (param i32 i32) (result i32))) (func (export "add_one") (param i32) (result i32) local.get 0 i32.const 1 call $sum)) """ ) # Now, let's create an import object, and register the `sum` # function. import_object = defaultdict(dict) import_object["math"]["sum"] = Function(store, sum) # Here we go, let's instantiate the module with the import object! instance = Instance(module, import_object) # Let's test it! assert instance.exports.add_one(41) == 42 ``` -------------------------------- ### Define WebAssembly MemoryType using Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer This example demonstrates how to create a `MemoryType` object in Python to describe a WebAssembly memory. It shows how to specify the minimum number of memory pages and whether the memory is shared. ```python from wasmer import MemoryType memory_type = MemoryType( minimum=1, shared=True ) ``` -------------------------------- ### Define WebAssembly FunctionType using Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer This example demonstrates how to create a `FunctionType` object in Python to represent the signature of a WebAssembly function. It shows how to specify the parameter types and result types for a function. ```python from wasmer import FunctionType, Type # Type: (i32, i32) -> i32 function_type = FunctionType( params=[Type.I32, Type.I32], results=[Type.I32] ) ``` -------------------------------- ### Define WebAssembly GlobalType using Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer This example illustrates how to define a `GlobalType` in Python, which describes a WebAssembly global variable. It shows how to specify the data type and whether the global is mutable. ```python from wasmer import GlobalType, Type # Describes a global of kind `i32` which is immutable. global_type = GlobalType(Type.I32, mutable=False) ``` -------------------------------- ### Importing Memory in Wasmer Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Illustrates importing and interacting with Wasm memory. The example shows how to import memory, define a Wasm module that increments a value in memory, and then use Python to view and modify the memory content. ```python from wasmer import Store, Module, Instance, Memory, MemoryType, ImportObject store = Store() module = Module( store, """ (module (import "env" "memory" (memory $memory 1)) (func (export "increment") i32.const 0 i32.const 0 i32.load ;; load 0 i32.const 1 i32.add ;; add 1 i32.store ;; store at 0 )) """ ) memory = Memory(store, MemoryType(minimum=1)) view = memory.uint8_view(offset=0) import_object = ImportObject() import_object.register( "env", { "memory": memory } ) instance = Instance(module, import_object) assert view[0] == 0 instance.exports.increment() assert view[0] == 1 instance.exports.increment() assert view[0] == 2 ``` -------------------------------- ### Python: Getting Wasmer Memory Data Size Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Demonstrates how to get the total size of the Wasmer Memory in bytes. This is useful for understanding the allocated memory footprint. It requires initializing a Store, MemoryType, and Memory. ```python from wasmer import Store, Memory, MemoryType store = Store() memory_type = MemoryType(minimum=3) memory = Memory(store, memory_type) assert memory.data_size == 196608 ``` -------------------------------- ### Wasmer Python Buffer Class Example Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Demonstrates the usage of the `Buffer` class in the Wasmer Python API to read and write raw bytes to memory. It shows how to create a memory buffer, write data using an `Int8Array` view, and then read the data back as a `bytearray`. This class implements the Python buffer protocol for seamless integration with standard Python byte manipulation tools. ```python from wasmer import Memory, MemoryType, Store store = Store() memory = Memory(store, MemoryType(minimum=128)) # Let's write data with a `Int8Array` view for example. int8 = memory.int8_view() int8[0] = 1 int8[1] = 2 int8[2] = 3 int8[3] = 0x57 int8[4] = 0x61 int8[5] = 0x73 int8[6] = 0x6d int8[7] = 0x65 int8[8] = 0x72 # Let's read data with a `Buffer` for example. byte_array = bytearray(memory.buffer) assert byte_array[0:3] == b'\x01\x02\x03' assert byte_array[3:9].decode() == 'Wasmer' ``` -------------------------------- ### Importing Globals in Wasmer Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Shows how to import and manage mutable global variables in WebAssembly using Python. The example demonstrates reading and writing to an imported global variable from both the Wasm module and the Python script. ```python from wasmer import Store, Module, Instance, ImportObject, Global, Value store = Store() module = Module( store, """ (module (import "env" "global" (global $global (mut i32))) (func (export "read_g") (result i32) global.get $global) (func (export "write_g") (param i32) local.get 0 global.set $global)) """ ) global_ = Global(store, Value.i32(7), mutable=True) import_object = ImportObject() import_object.register( "env", { "global": global_ } ) instance = Instance(module, import_object) assert instance.exports.read_g() == 7 global_.value = 153 assert instance.exports.read_g() == 153 instance.exports.write_g(11) assert global_.value == 11 ``` -------------------------------- ### Get Module Imports Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Returns a list of `ImportType` objects representing all imports of a WebAssembly module. The order is guaranteed to match the WebAssembly bytecode. ```python # See the `ImportType` class documentation for examples. ``` -------------------------------- ### Get Module Exports Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Returns a list of `ExportType` objects representing all exports of a WebAssembly module. The order is guaranteed to match the WebAssembly bytecode. ```python # See the `ExportType` class documentation for examples. ``` -------------------------------- ### Inspect WebAssembly Module Exports using Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer This example shows how to load a WebAssembly module and inspect its exports using the Wasmer Python API. It demonstrates how to access export names and their corresponding types (FunctionType, GlobalType, TableType, MemoryType) and validate their properties. ```python from wasmer import Store, Module, ExportType, FunctionType, GlobalType, TableType, MemoryType, Type module = Module( Store(), """ (module (func (export "function") (param i32 i64)) (global (export "global") i32 (i32.const 7)) (table (export "table") 0 funcref) (memory (export "memory") 1)) """ ) exports = module.exports assert isinstance(exports[0], ExportType) assert exports[0].name == "function" assert isinstance(exports[0].type, FunctionType) assert exports[0].type.params == [Type.I32, Type.I64] assert exports[0].type.results == [] assert exports[1].name == "global" assert isinstance(exports[1].type, GlobalType) assert exports[1].type.type == Type.I32 assert exports[1].type.mutable == False assert exports[2].name == "table" assert isinstance(exports[2].type, TableType) assert exports[2].type.type == Type.FUNC_REF assert exports[2].type.minimum == 0 assert exports[2].type.maximum == None assert exports[3].name == "memory" assert isinstance(exports[3].type, MemoryType) assert exports[3].type.minimum == 1 assert exports[3].type.maximum == None assert exports[3].type.shared == False ``` -------------------------------- ### Get or Set Module Name Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Retrieves or sets the name of a WebAssembly module. The name can be set during compilation or overwritten later. Not all modules have a name, in which case `None` is returned. Requires a Store object. ```python from wasmer import Store, Module store = Store() # Module with an existing name. assert Module(store, '(module $moduleName)').name == 'moduleName' # Module with no name. assert Module(store, '(module)').name == None # Change the module's name. module = Module(store, '(module $moduleName)') module.name = 'hello' assert module.name == 'hello' ``` -------------------------------- ### Inspect WebAssembly Module Imports using Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer This example demonstrates how to load a WebAssembly module and inspect its imports using the Wasmer Python API. It shows how to access import details such as module name, import name, and their corresponding types (FunctionType, GlobalType, TableType, MemoryType). ```python from wasmer import Store, Module, ImportType, FunctionType, GlobalType, TableType, MemoryType, Type module = Module( Store(), """ (module (import "ns" "function" (func)) (import "ns" "global" (global f32)) (import "ns" "table" (table 1 2 anyfunc)) (import "ns" "memory" (memory 3 4))) """ ) imports = module.imports assert isinstance(imports[0], ImportType) assert imports[0].module == "ns" assert imports[0].name == "function" assert isinstance(imports[0].type, FunctionType) assert imports[0].type.params == [] assert imports[0].type.results == [] assert imports[1].module == "ns" assert imports[1].name == "global" assert isinstance(imports[1].type, GlobalType) assert imports[1].type.type == Type.F32 assert imports[1].type.mutable == False assert imports[2].module == "ns" assert imports[2].name == "table" assert isinstance(imports[2].type, TableType) assert imports[2].type.type == Type.FUNC_REF assert imports[2].type.minimum == 1 assert imports[2].type.maximum == 2 assert imports[3].module == "ns" assert imports[3].name == "memory" assert isinstance(imports[3].type, MemoryType) assert imports[3].type.minimum == 3 assert imports[3].type.maximum == 4 assert imports[3].type.shared == False ``` -------------------------------- ### Python: Accessing Wasmer Table Type Information Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Illustrates how to get the type of a Wasmer Table, including the type of elements it holds (e.g., function references), and its minimum and maximum size. This requires instantiating a module with an exported table. ```python from wasmer import Store, Module, Instance, Table, Type module = Module(Store(), '(module (table (export "table") 2 funcref))') instance = Instance(module) table = instance.exports.table table_type = table.type assert table_type.type == Type.FUNC_REF assert table_type.minimum == 2 assert table_type.maximum == None ``` -------------------------------- ### Python: Getting Wasmer Table Size Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Shows how to retrieve the current size of a Wasmer Table in terms of the number of elements it contains. This is useful for understanding the table's current capacity. Requires a module with an exported table. ```python from wasmer import Store, Module, Instance, Table module = Module(Store(), '(module (table (export "table") 2 funcref))') instance = Instance(module) table = instance.exports.table assert table.size == 2 ``` -------------------------------- ### Python: Getting Wasmer Memory Size in Pages Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Shows how to retrieve the size of a Wasmer Memory in terms of WebAssembly pages (each page is 64KiB). This provides a measure of the memory's extent in page units. Initialization involves Store, MemoryType, and Memory. ```python from wasmer import Store, Memory, MemoryType store = Store() memory_type = MemoryType(minimum=3) memory = Memory(store, memory_type) assert memory.size == 3 ``` -------------------------------- ### Python: Accessing Wasmer Memory Type Information Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Illustrates how to retrieve the type information of a Wasmer Memory instance, including its minimum and maximum page limits, and whether it's shared. This requires a Module and Instance to get the exported memory. ```python from wasmer import Store, Module, Instance # Assuming 'tests/tests.wasm' is a valid WebAssembly file module = Module(Store(), open('tests/tests.wasm', 'rb').read()) instance = Instance(module) memory = instance.exports.memory memory_type = memory.type assert memory_type.minimum == 17 assert memory_type.maximum == None assert memory_type.shared == False ``` -------------------------------- ### Get Custom Sections by Name Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Retrieves custom sections from a WebAssembly module by their name. Returns a list of bytes, as a single name can correspond to multiple sections. An empty list signifies no sections found for the given name. Requires a Module object and the section name as input. ```python from wasmer import Store, Module module = Module(Store(), open('tests/custom_sections.wasm', 'rb').read()) assert module.custom_sections('easter_egg') == [b'Wasmer'] assert module.custom_sections('hello') == [b'World!'] assert module.custom_sections('foo') == [] ``` -------------------------------- ### Instantiate and Execute a WebAssembly Module in Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Demonstrates the basic usage of the Wasmer Python API to create a store, compile a WebAssembly module from WAT source, instantiate it, and call an exported function. Requires the `wasmer` library. ```python from wasmer import Store, Module, Instance # Create a store, which holds the engine, the compiler etc. store = Store() # Let's assume we don't have WebAssembly bytes at hand. We will # write WebAssembly manually. module = Module( store, """ (module (type (func (param i32 i32) (result i32))) (func (type 0) local.get 0 local.get 1 i32.add) (export "sum" (func 0))) """ ) # Instantiates the module. instance = Instance(module) # Now, let's execute the `sum` function. assert instance.exports.sum(1, 2) == 3 ``` -------------------------------- ### Initialize Universal Engine with LLVM Compiler Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Creates a Universal Wasmer engine configured to use the LLVM compiler. This allows the engine to compile WebAssembly code using LLVM optimizations. The `Compiler` class must be imported. ```python from wasmer import engine from wasmer_compiler_llvm import Compiler engine = engine.Universal(Compiler) ``` -------------------------------- ### Initialize Store with LLVM Compiler Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Initializes a `Store` object using the Universal engine combined with the LLVM compiler for ahead-of-time compilation. Requires the `wasmer` and `wasmer_compiler_llvm` libraries. ```python from wasmer import engine, Store from wasmer_compiler_llvm import Compiler store = Store(engine.Universal(Compiler)) ``` -------------------------------- ### Initialize Store with Universal Engine Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Initializes a `Store` object using the Universal engine, which operates in headless mode without a compiler. This is useful for basic runtime operations. Requires the `wasmer` library. ```python from wasmer import engine, Store store = Store(engine.Universal()) ``` -------------------------------- ### Create and Manage WebAssembly Memory Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Explains how to create a WebAssembly `Memory` instance with a specified minimum number of pages. It shows how to check the current size of the memory and how to grow it by a given number of pages. ```python from wasmer import Store, Memory, MemoryType store = Store() memory_type = MemoryType(minimum=3) memory = Memory(store, memory_type) assert memory.size == 3 ``` ```python from wasmer import Store, Memory, MemoryType store = Store() memory_type = MemoryType(minimum=3) memory = Memory(store, memory_type) assert memory.size == 3 memory.grow(2) assert memory.size == 5 ``` -------------------------------- ### Compile Module for Specific Target Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Configures a Wasmer Dylib engine with a specific target and compiler, then compiles a WebAssembly module for that target. Requires importing `engine`, `target`, `Store`, `Module`, and a compiler like `wasmer_compiler_cranelift`. ```python from wasmer import engine, target, Store, Module from wasmer_compiler_cranelift import Compiler # Build a triple from a string. triple = target.Triple('x86_64-linux-musl') # Build the CPU features (optional). cpu_features = target.CpuFeatures() cpu_features.add('sse2') # Build the target. target = target.Target(triple, cpu_features) # There we go. When creating the engine, pass the compiler _and_ # the target. engine = engine.Dylib(Compiler, target) # And finally, build the store with the engine. store = Store(engine) # Now, let's compile the module for the defined target. module = Module( store, """ (module (type $sum_t (func (param i32 i32) (result i32))) (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) local.get $x local.get $y i32.add) (export "sum" (func $sum_f))) """ ) ``` -------------------------------- ### Initialize Universal Wasmer Engine Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Initializes a Universal Wasmer engine. This engine can transform compilation code into artifacts and load artifacts for execution. It can be initialized with or without a compiler. ```python from wasmer import engine engine = engine.Universal() ``` -------------------------------- ### Define and Verify Python Function Signatures with Annotations Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Demonstrates how to define WebAssembly functions using Python type annotations and verify their corresponding Wasmer types. It maps Python types like `int` and `float` to Wasmer `Type.I32`, `Type.I64`, `Type.F32`, and `Type.F64`. It also shows how to handle functions returning tuples. ```python from wasmer import Store, Function, Type def sum(x: int, y: int) -> int: return x + y store = Store() function = Function(store, sum) function_type = function.type assert function_type.params == [Type.I32, Type.I32] assert function_type.results == [Type.I32] ``` ```python from wasmer import Store, Function, Type def swap(x: 'i32', y: 'i64') -> ('i64', 'i32'): return (y, x) store = Store() function = Function(store, swap) function_type = function.type assert function_type.params == [Type.I32, Type.I64] assert function_type.results == [Type.I64, Type.I32] ``` -------------------------------- ### Compile WebAssembly Module from Bytes or WAT in Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Shows how to compile a WebAssembly module in Python using the `wasmer.Module` class. Modules can be compiled from raw WebAssembly bytes or from WebAssembly Text (WAT) format. The compilation process includes validation using store features. ```python from wasmer import Store, Module store = Store() # Compile WebAssembly from bytes. module = Module(store, open('tests/tests.wasm', 'rb').read()) # Compile WebAssembly from WAT. module = Module(store, '(module)') ``` -------------------------------- ### Disassemble WebAssembly Binary to Text Format in Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Shows how to use the `wasm2wat` function from the `wasmer` library to convert WebAssembly binary format into human-readable WebAssembly text format (WAT). This is helpful for debugging or inspecting binary modules. ```python from wasmer import wasm2wat assert wasm2wat(b'\x00asm\x01\x00\x00\x00') == '(module)' ``` -------------------------------- ### Iterate Over WebAssembly Instance Exports in Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Demonstrates how to iterate through the exports of a Wasmer `Instance` in Python using the `ExportsIterator`. It collects the names of all exported items and asserts they match the expected list. ```python from wasmer import Store, Module, Instance, Exports, Function, Global, Table, Memory module = Module( Store(), """ (module (func (export "func") (param i32 i64)) (global (export "glob") i32 (i32.const 7)) (table (export "tab") 0 funcref) (memory (export "mem") 1)) """ ) instance = Instance(module) assert [name for (name, export) in instance.exports] == ["func", "glob", "tab", "mem"] ``` -------------------------------- ### Importing and Calling Functions in Wasmer Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Demonstrates how to import a function (`math.sum`) from a Wasm module and call it through an exported function (`add_one`). This involves defining the Python function, creating a Store, compiling the Module, setting up an ImportObject, and instantiating the module. ```python from wasmer import Store, Module, Instance, ImportObject, Function def sum(x: int, y: int) -> int: return x + y store = Store() module = Module( store, """ (module (import "math" "sum" (func $sum (param i32 i32) (result i32))) (func (export "add_one") (param i32) (result i32) local.get 0 i32.const 1 call $sum)) """ ) import_object = ImportObject() import_object.register( "math", { "sum": Function(store, sum) } ) instance = Instance(module, import_object) assert instance.exports.add_one(1) == 2 ``` -------------------------------- ### Create and Inspect Mutable Global Variables Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Shows how to create a mutable WebAssembly global variable. It verifies that the `mutable` attribute is correctly set to `True` and demonstrates how to set and retrieve its value. ```python from wasmer import Store, Global, Value store = Store() # Let's create an mutable global. global_ = Global(store, Value.i32(42), mutable=True) assert global_.mutable == True ``` ```python from wasmer import Store, Global, Value store = Store() global_ = Global(store, Value.i32(42), mutable=True) assert global_.value == 42 global_.value = 153 assert global_.value == 153 ``` ```python from wasmer import Store, Global, Value store = Store() global_ = Global(store, Value.i32(42), mutable=True) assert global_.mutable == True ``` -------------------------------- ### Python: Creating a Buffer for Wasmer Memory Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Demonstrates the creation of a Python buffer object for direct reading and writing of Wasmer memory data. This provides a low-level interface to the memory contents. Requires Store, MemoryType, and Memory initialization. ```python from wasmer import Store, Memory, MemoryType, Buffer store = Store() memory_type = MemoryType(minimum=3) memory = Memory(store, memory_type) assert isinstance(memory.buffer, Buffer) ``` -------------------------------- ### Wasmer Python API Import Source: https://wasmerio.github.io/wasmer-python/api/wasmer A simple Python code snippet showing how to import all symbols from the wasmer library and assign its docstring to a module-level variable. ```python from .wasmer import * __doc__ = wasmer.__doc__ ``` -------------------------------- ### Create i64 WebAssembly Value Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Constructs a WebAssembly i64 value. Use this when explicit type declaration for a 64-bit integer is required. Accepts an integer argument. ```python from wasmer import Value value = Value.i64(42) ``` -------------------------------- ### Inspect WebAssembly Instance Exports in Python Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Illustrates how to access and verify the types of exported items (function, global, table, memory) from a Wasmer `Instance` in Python. It checks that the exports match the expected `wasmer` types. ```python from wasmer import Store, Module, Instance, Exports, Function, Global, Table, Memory module = Module( Store(), """ (module (func (export "func") (param i32 i64)) (global (export "glob") i32 (i32.const 7)) (table (export "tab") 0 funcref) (memory (export "mem") 1)) """ ) instance = Instance(module) exports = instance.exports assert isinstance(exports, Exports) assert isinstance(exports.func, Function) assert isinstance(exports.glob, Global) assert isinstance(exports.tab, Table) assert isinstance(exports.mem, Memory) ``` -------------------------------- ### Serialize WebAssembly Module Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Serializes a WebAssembly module into a binary format, which can later be processed by `Module.deserialize`. This method takes no arguments and returns the module as bytes. ```python from wasmer import Store, Module store = Store() module = Module(Store(), '(module)') serialized_module = module.serialize() assert type(serialized_module) == bytes ``` -------------------------------- ### Create a Uint8 View of Memory Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Shows how to obtain a read-and-write view of the WebAssembly memory as an array of unsigned 8-bit integers (`uint8`). This view allows direct manipulation of memory bytes. ```python from wasmer import Store, Memory, MemoryType store = Store() memory_type = MemoryType(minimum=1) memory = Memory(store, memory_type) uint8_view = memory.uint8_view() # Example usage of the view (e.g., setting a byte) # uint8_view[0] = 10 # assert uint8_view[0] == 10 ``` -------------------------------- ### Python: Creating different data views (int8, uint16, etc.) for Wasmer Memory Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Shows how to create various typed array views (e.g., int8, uint16, float32) for accessing Wasmer memory data. Each view interprets the memory bytes according to its specific type. These views are created using methods like `int8_view`, `uint16_view`, etc., on a Memory object. ```python # Example for int8_view (other views follow a similar pattern): # from wasmer import Store, Memory, Int8Array # store = Store() # memory_type = MemoryType(minimum=3) # memory = Memory(store, memory_type) # assert isinstance(memory.int8_view(offset=10), Int8Array) # Example for float64_view: # from wasmer import Store, Memory, Float64Array # store = Store() # memory_type = MemoryType(minimum=3) # memory = Memory(store, memory_type) # assert isinstance(memory.float64_view(offset=20), Float64Array) ``` -------------------------------- ### Create f64 WebAssembly Value Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Generates a WebAssembly f64 floating-point value. Use this for explicit declaration of 64-bit floats when type inference is insufficient. It takes a float argument. ```python from wasmer import Value value = Value.f64(4.2) ``` -------------------------------- ### Registering Imports in ImportObject (Python) Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Illustrates how to register functions and memory into a specific namespace within an `ImportObject`. This is crucial for providing dependencies to a WebAssembly module. ```python from wasmer import Store, ImportObject, Function, Memory, MemoryType store = Store() def sum(x: int, y: int) -> int: return x + y import_object = ImportObject() import_object.register( "env", { "sum": Function(store, sum), "memory": Memory(store, MemoryType(minimum=1)) } ) ``` -------------------------------- ### Python: Using Dictionaries for Wasmer Imports Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Demonstrates the modern approach to providing imports for Wasmer modules using Python dictionaries. This replaces the deprecated `ImportObject` class and allows for structured import definitions, such as functions. ```python from wasmer import Store, Function def sum(x: int, y: int) -> int: return x + y store = Store() import_object = {} import_object["math"] = { "sum": Function(store, sum) } ``` -------------------------------- ### Create f32 WebAssembly Value Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Builds a WebAssembly f32 floating-point value. This method is employed when type inference for a 32-bit float fails. It requires a float as input. ```python from wasmer import Value value = Value.f32(4.2) ``` -------------------------------- ### Create and Inspect Immutable Global Variables Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Demonstrates the creation of an immutable WebAssembly global variable using `wasmer.Global` and `wasmer.Value`. It shows how to access the global's value and its type information, including whether it's mutable. ```python from wasmer import Store, Global, Value, Type store = Store() # Let's create an immutable global. global_ = Global(store, Value.i32(42)) global_type = global_.type assert global_.value == 42 assert global_type.type == Type.I32 assert global_type.mutable == False ``` -------------------------------- ### Create i32 WebAssembly Value Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Constructs a WebAssembly i32 value. This is useful when the type of a WebAssembly value cannot be inferred automatically. It takes an integer as input. ```python from wasmer import Value value = Value.i32(42) ``` -------------------------------- ### Access Memory from Instance Exports Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Illustrates how to retrieve a `Memory` object from the exports of a loaded WebAssembly `Instance`. This allows interaction with memory managed by the WebAssembly module. ```python from wasmer import Store, Module, Instance, Memory # Assuming 'tests/tests.wasm' is a valid wasm file # module = Module(Store(), open('tests/tests.wasm', 'rb').read()) # instance = Instance(module) # Example placeholder for module and instance loading # Replace with actual WASM loading if available class MockInstance: exports = type('obj', (object,), {'memory': Memory(Store(), MemoryType(minimum=1))})() instance = MockInstance() memory = instance.exports.memory assert isinstance(memory, Memory) ``` -------------------------------- ### Validate WebAssembly Module Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Validates a new WebAssembly Module against the Store's configuration. This is a fast, deterministic check ensuring enabled WebAssembly features are met. It takes raw WebAssembly bytes as input. ```python from wasmer import Store, Module assert Module.validate(Store(), wasm_bytes) ``` -------------------------------- ### Python: Accessing Uint8Array view of Wasmer Memory Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Demonstrates how to obtain a Uint8Array view for reading and writing memory data in Wasmer. This view allows for byte-level access to the memory. It requires a Store, MemoryType, and Memory object to be initialized. ```python from wasmer import Store, Memory, MemoryType, Uint8Array store = Store() memory_type = MemoryType(minimum=3) memory = Memory(store, memory_type) assert isinstance(memory.uint8_view(offset=42), Uint8Array) ``` -------------------------------- ### Int64Array Class Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Provides a read-and-write view over memory data as an Int64Array. It allows manipulation of memory as a typed array of 64-bit signed integers. ```APIDOC ## Int64Array Class ### Description Represents a read-and-write view over the data of a memory as an Int64Array. It is built by the `Memory.int64_view()` getter and implements the Python mapping protocol for accessing elements as 64-bit signed integers. ### Method N/A (Class definition) ### Endpoint N/A (Class definition) ### Parameters N/A ### Request Example ```python from wasmer import Store, Module, Instance # Assuming 'module' and 'instance' are already defined and exports.memory exists # module = Module(Store(), open('tests/tests.wasm', 'rb').read()) # instance = Instance(module) # exports = instance.exports # Example usage (replace with actual memory access if available) # memory_view = exports.memory.int64_view() # memory_view[0] = 9876543210 # print(memory_view[0]) # The provided example demonstrates Uint8Array, the principle for Int64Array is similar. # Example from provided text: # module = Module(Store(), open('tests/tests.wasm', 'rb').read()) # instance = Instance(module) # exports = instance.exports # # pointer = exports.string() # memory = exports.memory.uint8_view(offset=pointer) # nth = 0 # string = '' # # while (0 != memory[nth]): # string += chr(memory[nth]) # nth += 1 # # assert string == 'Hello, World!' ``` ### Response #### Success Response (N/A - Class instantiation) N/A #### Response Example N/A ``` -------------------------------- ### Buffer Class Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Represents a read-and-write buffer over memory data. It implements the Python buffer protocol for direct byte manipulation. ```APIDOC ## Buffer Class ### Description Represents a read-and-write buffer over data of a memory. It is built by the `Memory.buffer` getter and implements the Python buffer protocol, allowing direct interaction with bytes using `bytes`, `bytearray`, or `memoryview`. ### Method N/A (Class definition) ### Endpoint N/A (Class definition) ### Parameters N/A ### Request Example ```python from wasmer import Memory, MemoryType, Store store = Store() memory = Memory(store, MemoryType(minimum=128)) # Let's write data with a `Int8Array` view for example. int8 = memory.int8_view() int8[0] = 1 int8[1] = 2 int8[2] = 3 int8[3] = 0x57 int8[4] = 0x61 int8[5] = 0x73 int8[6] = 0x6d int8[7] = 0x65 int8[8] = 0x72 # Let's read data with a `Buffer` for example. byte_array = bytearray(memory.buffer) assert byte_array[0:3] == b'\x01\x02\x03' assert byte_array[3:9].decode() == 'Wasmer' ``` ### Response #### Success Response (N/A - Class instantiation) N/A #### Response Example N/A ``` -------------------------------- ### Access Wasmer Function Type Information Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Illustrates how to retrieve the `FunctionType` of a Wasmer function, whether defined directly or exported from an instance. This allows inspection of the function's parameter and result types. ```python from wasmer import Store, Module, Instance, FunctionType, Type module = Module( Store(), """ (module (type (func (param i32 i32) (result i32))) (func (type 0) local.get 0 local.get 1 i32.add) (export "sum" (func 0))) """ ) instance = Instance(module) sum = instance.exports.sum sum_type = sum.type assert isinstance(sum_type, FunctionType) assert sum_type.params == [Type.I32, Type.I32] assert sum_type.results == [Type.I32] ``` -------------------------------- ### Deserialize Serialized Module Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Deserializes a previously serialized module binary back into a `Module` object. This operation is inherently unsafe as it directly deserializes provided bytes into Rust objects, posing a potential security risk if the bytes are compromised. Requires a Store and the serialized bytes as input. ```python from wasmer import Store, Module store = Store() module = Module( store, """ (module (func (export "function") (param i32 i64))) """ ) serialized_module = module.serialize() del module module = Module.deserialize(store, serialized_module) del serialized_module assert isinstance(module, Module) ``` -------------------------------- ### Float64Array Class Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Provides a read-and-write view over memory data as a Float64Array. It allows manipulation of memory as a typed array of 64-bit floating-point numbers. ```APIDOC ## Float64Array Class ### Description Represents a read-and-write view over the data of a memory as a Float64Array. It is built by the `Memory.float64_view()` getter and implements the Python mapping protocol for accessing elements as 64-bit floating-point numbers. ### Method N/A (Class definition) ### Endpoint N/A (Class definition) ### Parameters N/A ### Request Example ```python from wasmer import Store, Module, Instance # Assuming 'module' and 'instance' are already defined and exports.memory exists # module = Module(Store(), open('tests/tests.wasm', 'rb').read()) # instance = Instance(module) # exports = instance.exports # Example usage (replace with actual memory access if available) # memory_view = exports.memory.float64_view() # memory_view[0] = 1.0 # print(memory_view[0]) # The provided example demonstrates Uint8Array, the principle for Float64Array is similar. # Example from provided text: # module = Module(Store(), open('tests/tests.wasm', 'rb').read()) # instance = Instance(module) # exports = instance.exports # # pointer = exports.string() # memory = exports.memory.uint8_view(offset=pointer) # nth = 0 # string = '' # # while (0 != memory[nth]): # string += chr(memory[nth]) # nth += 1 # # assert string == 'Hello, World!' ``` ### Response #### Success Response (N/A - Class instantiation) N/A #### Response Example N/A ``` -------------------------------- ### Int32Array Class Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Provides a read-and-write view over memory data as an Int32Array. It allows manipulation of memory as a typed array of 32-bit signed integers. ```APIDOC ## Int32Array Class ### Description Represents a read-and-write view over the data of a memory as an Int32Array. It is built by the `Memory.int32_view()` getter and implements the Python mapping protocol for accessing elements as 32-bit signed integers. ### Method N/A (Class definition) ### Endpoint N/A (Class definition) ### Parameters N/A ### Request Example ```python from wasmer import Store, Module, Instance # Assuming 'module' and 'instance' are already defined and exports.memory exists # module = Module(Store(), open('tests/tests.wasm', 'rb').read()) # instance = Instance(module) # exports = instance.exports # Example usage (replace with actual memory access if available) # memory_view = exports.memory.int32_view() # memory_view[0] = 12345 # print(memory_view[0]) # The provided example demonstrates Uint8Array, the principle for Int32Array is similar. # Example from provided text: # module = Module(Store(), open('tests/tests.wasm', 'rb').read()) # instance = Instance(module) # exports = instance.exports # # pointer = exports.string() # memory = exports.memory.uint8_view(offset=pointer) # nth = 0 # string = '' # # while (0 != memory[nth]): # string += chr(memory[nth]) # nth += 1 # # assert string == 'Hello, World!' ``` ### Response #### Success Response (N/A - Class instantiation) N/A #### Response Example N/A ``` -------------------------------- ### Create v128 WebAssembly Value Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Creates a WebAssembly v128 vector value. This is necessary when the type of a v128 value needs to be explicitly defined. It accepts an integer value. ```python from wasmer import Value value = Value.v128(42) ``` -------------------------------- ### Int16Array Class Source: https://wasmerio.github.io/wasmer-python/api/wasmer/wasmer Provides a read-and-write view over memory data as an Int16Array. It allows manipulation of memory as a typed array of 16-bit signed integers. ```APIDOC ## Int16Array Class ### Description Represents a read-and-write view over the data of a memory as an Int16Array. It is built by the `Memory.int16_view()` getter and implements the Python mapping protocol for accessing elements as 16-bit signed integers. ### Method N/A (Class definition) ### Endpoint N/A (Class definition) ### Parameters N/A ### Request Example ```python from wasmer import Store, Module, Instance # Assuming 'module' and 'instance' are already defined and exports.memory exists # module = Module(Store(), open('tests/tests.wasm', 'rb').read()) # instance = Instance(module) # exports = instance.exports # Example usage (replace with actual memory access if available) # memory_view = exports.memory.int16_view() # memory_view[0] = 100 # print(memory_view[0]) # The provided example demonstrates Uint8Array, the principle for Int16Array is similar. # Example from provided text: # module = Module(Store(), open('tests/tests.wasm', 'rb').read()) # instance = Instance(module) # exports = instance.exports # # pointer = exports.string() # memory = exports.memory.uint8_view(offset=pointer) # nth = 0 # string = '' # # while (0 != memory[nth]): # string += chr(memory[nth]) # nth += 1 # # assert string == 'Hello, World!' ``` ### Response #### Success Response (N/A - Class instantiation) N/A #### Response Example N/A ```