Package wasmtime

Python bindings for the Wasmtime project

This library binds the Wasmtime project's C API to provide an implementation of a WebAssembly JIT compiler to Python. You can validate, compile, instantiate, and interact with WebAssembly modules via this library.

The API of this library is intended to be very similar to the wasmtime Rust crate, so if you find the docs are lacking here feel free to consult that documentation as well. While not exactly the same the two libraries are intended to be quite similar.

Expand source code
"""
Python bindings for the [Wasmtime project]

[Wasmtime project]: https://github.com/bytecodealliance/wasmtime

This library binds the [Wasmtime project]'s C API to provide an implementation
of a WebAssembly JIT compiler to Python. You can validate, compile, instantiate,
and interact with WebAssembly modules via this library.

The API of this library is intended to be very similar to the [`wasmtime` Rust
crate](https://docs.rs/wasmtime), so if you find the docs are lacking here feel
free to consult that documentation as well. While not exactly the same the two
libraries are intended to be quite similar.
"""

from ._error import WasmtimeError
from ._config import Config
from ._engine import Engine
from ._store import Store, Storelike
from ._types import FuncType, GlobalType, MemoryType, TableType
from ._types import ValType, Limits, ImportType, ExportType, ModuleType, InstanceType
from ._wat2wasm import wat2wasm
from ._module import Module
from ._value import Val, IntoVal
from ._trap import Trap, Frame, ExitTrap, TrapCode
from ._func import Func, Caller
from ._globals import Global
from ._table import Table
from ._memory import Memory
from ._instance import Instance
from ._wasi import WasiConfig
from ._linker import Linker

__all__ = [
    'wat2wasm',
    'Config',
    'Engine',
    'Store',
    'FuncType',
    'GlobalType',
    'MemoryType',
    'TableType',
    'ValType',
    'Limits',
    'ImportType',
    'ExportType',
    'IntoVal',
    'Val',
    'Func',
    'Caller',
    'Table',
    'Memory',
    'Global',
    'Trap',
    'TrapCode',
    'ExitTrap',
    'Frame',
    'Module',
    'Instance',
    'WasiConfig',
    'Linker',
    'WasmtimeError',
]

Sub-modules

wasmtime.loader

This module is a custom loader for Python which enables importing wasm files directly into Python programs simply through usage of the import

Functions

def wat2wasm(wat: Union[str, bytes]) ‑> bytearray

Converts the WebAssembly Text format to the binary format.

This function is intended to be a convenience function for local development and you likely don't want to use it extensively in production. It's much faster to parse and compile the binary format than it is to process the text format.

Takes a str as input, raises an error if it fails to parse, and returns a bytes if conversion/parsing was successful.

>>> wat2wasm('(module)')
bytearray(b'\x00asm\x01\x00\x00\x00')
Expand source code
def wat2wasm(wat: typing.Union[str, bytes]) -> bytearray:
    """
    Converts the [WebAssembly Text format][wat] to the binary format.

    This function is intended to be a convenience function for local
    development and you likely don't want to use it extensively in production.
    It's much faster to parse and compile the binary format than it is to
    process the text format.

    Takes a `str` as input, raises an error if it fails to parse, and returns
    a `bytes` if conversion/parsing was successful.

    >>> wat2wasm('(module)')
    bytearray(b'\\x00asm\\x01\\x00\\x00\\x00')

    [wat]: https://webassembly.github.io/spec/core/text/index.html
    """

    if isinstance(wat, str):
        wat = wat.encode('utf8')
    wat_buffer = create_string_buffer(wat)
    wasm = ffi.wasm_byte_vec_t()
    error = ffi.wasmtime_wat2wasm(wat_buffer, len(wat), byref(wasm))
    if error:
        raise WasmtimeError._from_ptr(error)
    else:
        ret = ffi.to_bytes(wasm)
        ffi.wasm_byte_vec_delete(byref(wasm))
        return ret

Classes

class Caller (ptr: )
Expand source code
class Caller:
    _context: "pointer[ffi.wasmtime_context_t]"

    def __init__(self, ptr: pointer):
        self._ptr = ptr

    def __getitem__(self, name: str) -> AsExtern:
        """
        Looks up an export with `name` on the calling module.

        If `name` isn't defined on the calling module, or if the caller has gone
        away for some reason, then this will raise a `KeyError`. For more
        information about when this could fail see the `get` method which
        returns `None` on failure.
        """

        ret = self.get(name)
        if ret is None:
            raise KeyError("failed to find export {}".format(name))
        return ret

    def get(self, name: str) -> Optional[AsExtern]:
        """
        Looks up an export with `name` on the calling module.

        May return `None` if the export isn't found, if it's not a memory (for
        now), or if the caller has gone away and this `Caller` object has
        persisted too long.
        """

        # First convert to a raw name so we can typecheck our argument
        name_bytes = name.encode('utf-8')
        name_buf = ffi.create_string_buffer(name_bytes)

        # Next see if we've been invalidated
        if not hasattr(self, '_ptr'):
            return None

        # And if we're not invalidated we can perform the actual lookup
        item = ffi.wasmtime_extern_t()
        ok = ffi.wasmtime_caller_export_get(self._ptr, name_buf, len(name_bytes), byref(item))
        if ok:
            return wrap_extern(item)
        else:
            return None

Methods

def get(self, name: str) ‑> Union[FuncTableMemoryGlobalInstanceModule, ForwardRef(None)]

Looks up an export with name on the calling module.

May return None if the export isn't found, if it's not a memory (for now), or if the caller has gone away and this Caller object has persisted too long.

Expand source code
def get(self, name: str) -> Optional[AsExtern]:
    """
    Looks up an export with `name` on the calling module.

    May return `None` if the export isn't found, if it's not a memory (for
    now), or if the caller has gone away and this `Caller` object has
    persisted too long.
    """

    # First convert to a raw name so we can typecheck our argument
    name_bytes = name.encode('utf-8')
    name_buf = ffi.create_string_buffer(name_bytes)

    # Next see if we've been invalidated
    if not hasattr(self, '_ptr'):
        return None

    # And if we're not invalidated we can perform the actual lookup
    item = ffi.wasmtime_extern_t()
    ok = ffi.wasmtime_caller_export_get(self._ptr, name_buf, len(name_bytes), byref(item))
    if ok:
        return wrap_extern(item)
    else:
        return None
class Config

Global configuration, used to create an Engine.

A Config houses a number of configuration options which tweaks how wasm code is compiled or generated.

Expand source code
class Config:
    """
    Global configuration, used to create an `Engine`.

    A `Config` houses a number of configuration options which tweaks how wasm
    code is compiled or generated.
    """

    def __init__(self) -> None:
        self._ptr = ffi.wasm_config_new()

    @setter_property
    def debug_info(self, enable: bool) -> None:
        """
        Configures whether DWARF debug information is emitted for the generated
        code. This can improve profiling and the debugging experience.
        """

        if not isinstance(enable, bool):
            raise TypeError('expected a bool')
        ffi.wasmtime_config_debug_info_set(self._ptr, enable)

    @setter_property
    def wasm_threads(self, enable: bool) -> None:
        """
        Configures whether the wasm [threads proposal] is enabled.

        [threads proposal]: https://github.com/webassembly/threads
        """

        if not isinstance(enable, bool):
            raise TypeError('expected a bool')
        ffi.wasmtime_config_wasm_threads_set(self._ptr, enable)

    @setter_property
    def wasm_reference_types(self, enable: bool) -> None:
        """
        Configures whether the wasm [reference types proposal] is enabled.

        [reference types proposal]: https://github.com/webassembly/reference-types
        """

        if not isinstance(enable, bool):
            raise TypeError('expected a bool')
        ffi.wasmtime_config_wasm_reference_types_set(self._ptr, enable)

    @setter_property
    def wasm_simd(self, enable: bool) -> None:
        """
        Configures whether the wasm [SIMD proposal] is enabled.

        [SIMD proposal]: https://github.com/webassembly/simd
        """

        if not isinstance(enable, bool):
            raise TypeError('expected a bool')
        ffi.wasmtime_config_wasm_simd_set(self._ptr, enable)

    @setter_property
    def wasm_bulk_memory(self, enable: bool) -> None:
        """
        Configures whether the wasm [bulk memory proposal] is enabled.

        [bulk memory proposal]: https://github.com/webassembly/bulk-memory
        """

        if not isinstance(enable, bool):
            raise TypeError('expected a bool')
        ffi.wasmtime_config_wasm_bulk_memory_set(self._ptr, enable)

    @setter_property
    def wasm_multi_value(self, enable: bool) -> None:
        """
        Configures whether the wasm [multi value proposal] is enabled.

        [multi value proposal]: https://github.com/webassembly/multi-value
        """

        if not isinstance(enable, bool):
            raise TypeError('expected a bool')
        ffi.wasmtime_config_wasm_multi_value_set(self._ptr, enable)

    @setter_property
    def wasm_module_linking(self, enable: bool) -> None:
        """
        Configures whether the wasm [module linking proposal] is enabled.

        [module linking proposal]: https://github.com/webassembly/module-linking
        """

        if not isinstance(enable, bool):
            raise TypeError('expected a bool')
        ffi.wasmtime_config_wasm_module_linking_set(self._ptr, enable)

    @setter_property
    def wasm_multi_memory(self, enable: bool) -> None:
        """
        Configures whether the wasm [multi memory proposal] is enabled.

        [multi memory proposal]: https://github.com/webassembly/multi-memory
        """

        if not isinstance(enable, bool):
            raise TypeError('expected a bool')
        ffi.wasmtime_config_wasm_multi_memory_set(self._ptr, enable)

    @setter_property
    def wasm_memory64(self, enable: bool) -> None:
        """
        Configures whether the wasm [memory64 proposal] is enabled.

        [memory64 proposal]: https://github.com/webassembly/memory64
        """

        if not isinstance(enable, bool):
            raise TypeError('expected a bool')
        ffi.wasmtime_config_wasm_memory64_set(self._ptr, enable)

    @setter_property
    def strategy(self, strategy: str) -> None:
        """
        Configures the compilation strategy used for wasm code.

        Acceptable values for `strategy` are:

        * `"auto"`
        * `"cranelift"`
        """

        if strategy == "auto":
            error = ffi.wasmtime_config_strategy_set(self._ptr, 0)
        elif strategy == "cranelift":
            error = ffi.wasmtime_config_strategy_set(self._ptr, 1)
        else:
            raise WasmtimeError("unknown strategy: " + str(strategy))
        if error:
            raise WasmtimeError._from_ptr(error)

    @setter_property
    def cranelift_debug_verifier(self, enable: bool) -> None:
        if not isinstance(enable, bool):
            raise TypeError('expected a bool')
        ffi.wasmtime_config_cranelift_debug_verifier_set(self._ptr, enable)

    @setter_property
    def cranelift_opt_level(self, opt_level: str) -> None:
        if opt_level == "none":
            ffi.wasmtime_config_cranelift_opt_level_set(self._ptr, 0)
        elif opt_level == "speed":
            ffi.wasmtime_config_cranelift_opt_level_set(self._ptr, 1)
        elif opt_level == "speed_and_size":
            ffi.wasmtime_config_cranelift_opt_level_set(self._ptr, 2)
        else:
            raise WasmtimeError("unknown opt level: " + str(opt_level))

    @setter_property
    def profiler(self, profiler: str) -> None:
        if profiler == "none":
            error = ffi.wasmtime_config_profiler_set(self._ptr, 0)
        elif profiler == "jitdump":
            error = ffi.wasmtime_config_profiler_set(self._ptr, 1)
        else:
            raise WasmtimeError("unknown profiler: " + str(profiler))
        if error:
            raise WasmtimeError._from_ptr(error)

    @setter_property
    def cache(self, enabled: typing.Union[bool, str]) -> None:
        """
        Configures whether code caching is enabled for this `Config`.

        The value `True` can be passed in here to enable the default caching
        configuration and location, or a path to a file can be passed in which
        is a path to a TOML configuration file for the cache.

        More information about cache configuration can be found at
        https://bytecodealliance.github.io/wasmtime/cli-cache.html
        """

        if isinstance(enabled, bool):
            if not enabled:
                raise WasmtimeError("caching cannot be explicitly disabled")
            error = ffi.wasmtime_config_cache_config_load(self._ptr, None)
        elif isinstance(enabled, str):
            error = ffi.wasmtime_config_cache_config_load(self._ptr,
                                                          c_char_p(enabled.encode('utf-8')))
        else:
            raise TypeError("expected string or bool")
        if error:
            raise WasmtimeError._from_ptr(error)

    @setter_property
    def interruptable(self, enabled: bool) -> None:
        """
        Configures whether wasm execution can be interrupted via interrupt
        handles.
        """

        if enabled:
            val = 1
        else:
            val = 0
        ffi.wasmtime_config_interruptable_set(self._ptr, val)

    @setter_property
    def consume_fuel(self, instances: bool) -> None:
        """
        Configures whether wasm code will consume *fuel* as part of its
        execution.

        Fuel consumption allows WebAssembly to trap when fuel runs out.
        Currently stores start with 0 fuel if this is enabled.
        """
        if not isinstance(instances, bool):
            raise TypeError('expected an bool')
        ffi.wasmtime_config_consume_fuel_set(self._ptr, instances)

    def __del__(self) -> None:
        if hasattr(self, '_ptr'):
            ffi.wasm_config_delete(self._ptr)

Instance variables

var cache

Configures whether code caching is enabled for this Config.

The value True can be passed in here to enable the default caching configuration and location, or a path to a file can be passed in which is a path to a TOML configuration file for the cache.

More information about cache configuration can be found at https://bytecodealliance.github.io/wasmtime/cli-cache.html

Note that this field can only be set, it cannot be read

var consume_fuel

Configures whether wasm code will consume fuel as part of its execution.

Fuel consumption allows WebAssembly to trap when fuel runs out. Currently stores start with 0 fuel if this is enabled.

Note that this field can only be set, it cannot be read

var cranelift_debug_verifier
var cranelift_opt_level
var debug_info

Configures whether DWARF debug information is emitted for the generated code. This can improve profiling and the debugging experience.

Note that this field can only be set, it cannot be read

var interruptable

Configures whether wasm execution can be interrupted via interrupt handles.

Note that this field can only be set, it cannot be read

var profiler
var strategy

Configures the compilation strategy used for wasm code.

Acceptable values for strategy are:

  • "auto"
  • "cranelift"

Note that this field can only be set, it cannot be read

var wasm_bulk_memory

Configures whether the wasm bulk memory proposal is enabled.

Note that this field can only be set, it cannot be read

var wasm_memory64

Configures whether the wasm memory64 proposal is enabled.

Note that this field can only be set, it cannot be read

var wasm_module_linking

Configures whether the wasm module linking proposal is enabled.

Note that this field can only be set, it cannot be read

var wasm_multi_memory

Configures whether the wasm multi memory proposal is enabled.

Note that this field can only be set, it cannot be read

var wasm_multi_value

Configures whether the wasm multi value proposal is enabled.

Note that this field can only be set, it cannot be read

var wasm_reference_types

Configures whether the wasm reference types proposal is enabled.

Note that this field can only be set, it cannot be read

var wasm_simd

Configures whether the wasm SIMD proposal is enabled.

Note that this field can only be set, it cannot be read

var wasm_threads

Configures whether the wasm threads proposal is enabled.

Note that this field can only be set, it cannot be read

class Engine (config: wasmtime._config.Config = None)
Expand source code
class Engine:
    def __init__(self, config: Config = None):
        if config is None:
            self._ptr = ffi.wasm_engine_new()
        elif not isinstance(config, Config):
            raise TypeError("expected Config")
        elif not hasattr(config, '_ptr'):
            raise WasmtimeError("Config already used")
        else:
            ptr = config._ptr
            delattr(config, '_ptr')
            self._ptr = ffi.wasm_engine_new_with_config(ptr)

    def __del__(self) -> None:
        if hasattr(self, '_ptr'):
            ffi.wasm_engine_delete(self._ptr)
class ExitTrap (message: str)

A special type of Trap which represents the process exiting via WASI's proc_exit function call.

Whenever a WASI program exits via proc_exit a trap is raised, but the trap will have this type instead of Trap, so you can catch just this type instead of all traps (if desired). Exit traps have a code associated with them which is the exit code provided at exit.

Note that ExitTrap is a subclass of Trap, so if you catch a trap you'll also catch ExitTrap.

Creates a new trap with the given message

Expand source code
class ExitTrap(Trap):
    """
    A special type of `Trap` which represents the process exiting via WASI's
    `proc_exit` function call.

    Whenever a WASI program exits via `proc_exit` a trap is raised, but the
    trap will have this type instead of `Trap`, so you can catch just this
    type instead of all traps (if desired). Exit traps have a `code` associated
    with them which is the exit code provided at exit.

    Note that `ExitTrap` is a subclass of `Trap`, so if you catch a trap you'll
    also catch `ExitTrap`.
    """
    code: int
    pass

Ancestors

  • wasmtime._trap.Trap
  • builtins.Exception
  • builtins.BaseException

Class variables

var code : int
class ExportType
Expand source code
class ExportType:
    _ptr: "pointer[ffi.wasm_exporttype_t]"
    _owner: Optional[Any]

    @classmethod
    def _from_ptr(cls, ptr: 'pointer[ffi.wasm_exporttype_t]', owner: Optional[Any]) -> "ExportType":
        ty: "ExportType" = cls.__new__(cls)
        if not isinstance(ptr, POINTER(ffi.wasm_exporttype_t)):
            raise TypeError("wrong pointer type")
        ty._ptr = ptr
        ty._owner = owner
        return ty

    @property
    def name(self) -> str:
        """
        Returns the name in the modulethis export type refers to
        """
        return ffi.to_str(ffi.wasm_exporttype_name(self._ptr).contents)

    @property
    def type(self) -> "AsExternType":
        """
        Returns the type that this export refers to
        """
        ptr = ffi.wasm_exporttype_type(self._ptr)
        return wrap_externtype(ptr, self._owner or self)

    def __del__(self) -> None:
        if self._owner is None:
            ffi.wasm_exporttype_delete(self._ptr)

Instance variables

var name : str

Returns the name in the modulethis export type refers to

Expand source code
@property
def name(self) -> str:
    """
    Returns the name in the modulethis export type refers to
    """
    return ffi.to_str(ffi.wasm_exporttype_name(self._ptr).contents)
var type : Union[wasmtime._types.FuncType, wasmtime._types.TableType, wasmtime._types.MemoryType, wasmtime._types.GlobalType, wasmtime._types.InstanceType, wasmtime._types.ModuleType]

Returns the type that this export refers to

Expand source code
@property
def type(self) -> "AsExternType":
    """
    Returns the type that this export refers to
    """
    ptr = ffi.wasm_exporttype_type(self._ptr)
    return wrap_externtype(ptr, self._owner or self)
class Frame
Expand source code
class Frame:
    _ptr: "pointer[ffi.wasm_frame_t]"
    _owner: Optional[Any]

    @classmethod
    def _from_ptr(cls, ptr: "pointer[ffi.wasm_frame_t]", owner: Optional[Any]) -> "Frame":
        ty: "Frame" = cls.__new__(cls)
        if not isinstance(ptr, POINTER(ffi.wasm_frame_t)):
            raise TypeError("wrong pointer type")
        ty._ptr = ptr
        ty._owner = owner
        return ty

    @property
    def func_index(self) -> int:
        """
        Returns the function index this frame corresponds to in its wasm module
        """

        return ffi.wasm_frame_func_index(self._ptr)

    @property
    def func_name(self) -> Optional[str]:
        """
        Returns the name of the function this frame corresponds to

        May return `None` if no name can be inferred
        """

        ptr = ffi.wasmtime_frame_func_name(self._ptr)
        if ptr:
            return ffi.to_str(ptr.contents)
        else:
            return None

    @property
    def module_name(self) -> Optional[str]:
        """
        Returns the name of the module this frame corresponds to

        May return `None` if no name can be inferred
        """

        ptr = ffi.wasmtime_frame_module_name(self._ptr)
        if ptr:
            return ffi.to_str(ptr.contents)
        else:
            return None

    @property
    def module_offset(self) -> int:
        """
        Returns the offset of this frame's program counter into the original
        wasm source module.
        """

        return ffi.wasm_frame_module_offset(self._ptr)

    @property
    def func_offset(self) -> int:
        """
        Returns the offset of this frame's program counter into the original
        wasm function.
        """

        return ffi.wasm_frame_func_offset(self._ptr)

    def __del__(self) -> None:
        if self._owner is None:
            ffi.wasm_frame_delete(self._ptr)

Instance variables

var func_index : int

Returns the function index this frame corresponds to in its wasm module

Expand source code
@property
def func_index(self) -> int:
    """
    Returns the function index this frame corresponds to in its wasm module
    """

    return ffi.wasm_frame_func_index(self._ptr)
var func_name : Optional[str]

Returns the name of the function this frame corresponds to

May return None if no name can be inferred

Expand source code
@property
def func_name(self) -> Optional[str]:
    """
    Returns the name of the function this frame corresponds to

    May return `None` if no name can be inferred
    """

    ptr = ffi.wasmtime_frame_func_name(self._ptr)
    if ptr:
        return ffi.to_str(ptr.contents)
    else:
        return None
var func_offset : int

Returns the offset of this frame's program counter into the original wasm function.

Expand source code
@property
def func_offset(self) -> int:
    """
    Returns the offset of this frame's program counter into the original
    wasm function.
    """

    return ffi.wasm_frame_func_offset(self._ptr)
var module_name : Optional[str]

Returns the name of the module this frame corresponds to

May return None if no name can be inferred

Expand source code
@property
def module_name(self) -> Optional[str]:
    """
    Returns the name of the module this frame corresponds to

    May return `None` if no name can be inferred
    """

    ptr = ffi.wasmtime_frame_module_name(self._ptr)
    if ptr:
        return ffi.to_str(ptr.contents)
    else:
        return None
var module_offset : int

Returns the offset of this frame's program counter into the original wasm source module.

Expand source code
@property
def module_offset(self) -> int:
    """
    Returns the offset of this frame's program counter into the original
    wasm source module.
    """

    return ffi.wasm_frame_module_offset(self._ptr)
class Func (store: Union[wasmtime._store.Store, ForwardRef('Caller')], ty: wasmtime._types.FuncType, func: Callable, access_caller: bool = False)

Creates a new func in store with the given ty which calls the closure given

The func is called with the parameters natively and they'll have native Python values rather than being wrapped in Val. If access_caller is set to True then the first argument given to func is an instance of type Caller below.

Expand source code
class Func:
    _func: ffi.wasmtime_func_t

    def __init__(self, store: Storelike, ty: FuncType, func: Callable, access_caller: bool = False):
        """
        Creates a new func in `store` with the given `ty` which calls the closure
        given

        The `func` is called with the parameters natively and they'll have native
        Python values rather than being wrapped in `Val`. If `access_caller` is
        set to `True` then the first argument given to `func` is an instance of
        type `Caller` below.
        """

        if not isinstance(store, Store):
            raise TypeError("expected a Store")
        if not isinstance(ty, FuncType):
            raise TypeError("expected a FuncType")
        idx = FUNCTIONS.allocate((func, ty.results, access_caller))
        _func = ffi.wasmtime_func_t()
        ffi.wasmtime_func_new(
            store._context,
            ty._ptr,
            trampoline,
            idx,
            finalize,
            byref(_func))
        self._func = _func

    @classmethod
    def _from_raw(cls, func: ffi.wasmtime_func_t) -> "Func":
        ty: "Func" = cls.__new__(cls)
        ty._func = func
        return ty

    def type(self, store: Storelike) -> FuncType:
        """
        Gets the type of this func as a `FuncType`
        """
        ptr = ffi.wasmtime_func_type(store._context, byref(self._func))
        return FuncType._from_ptr(ptr, None)

    def __call__(self, store: Storelike, *params: IntoVal) -> Union[IntoVal, Sequence[IntoVal], None]:
        """
        Calls this function with the given parameters

        Parameters can either be a `Val` or a native python value which can be
        converted to a `Val` of the corresponding correct type

        Returns `None` if this func has 0 return types
        Returns a single value if the func has 1 return type
        Returns a list if the func has more than 1 return type

        Note that you can also use the `__call__` method and invoke a `Func` as
        if it were a function directly.
        """

        ty = self.type(store)
        param_tys = ty.params
        if len(params) > len(param_tys):
            raise WasmtimeError("too many parameters provided: given %s, expected %s" %
                                (len(params), len(param_tys)))
        if len(params) < len(param_tys):
            raise WasmtimeError("too few parameters provided: given %s, expected %s" %
                                (len(params), len(param_tys)))

        param_vals = [Val._convert(ty, params[i]) for i, ty in enumerate(param_tys)]
        params_ptr = (ffi.wasmtime_val_t * len(params))()
        for i, val in enumerate(param_vals):
            params_ptr[i] = val._unwrap_raw()

        result_tys = ty.results
        results_ptr = (ffi.wasmtime_val_t * len(result_tys))()

        with enter_wasm(store) as trap:
            error = ffi.wasmtime_func_call(
                store._context,
                byref(self._func),
                params_ptr,
                len(params),
                results_ptr,
                len(result_tys),
                trap)
            if error:
                raise WasmtimeError._from_ptr(error)

        results = []
        for i in range(0, len(result_tys)):
            results.append(Val(results_ptr[i]).value)
        if len(results) == 0:
            return None
        elif len(results) == 1:
            return results[0]
        else:
            return results

    def _as_extern(self) -> ffi.wasmtime_extern_t:
        union = ffi.wasmtime_extern_union(func=self._func)
        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_FUNC, union)

Methods

def type(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> wasmtime._types.FuncType

Gets the type of this func as a FuncType

Expand source code
def type(self, store: Storelike) -> FuncType:
    """
    Gets the type of this func as a `FuncType`
    """
    ptr = ffi.wasmtime_func_type(store._context, byref(self._func))
    return FuncType._from_ptr(ptr, None)
class FuncType (params: List[wasmtime._types.ValType], results: List[wasmtime._types.ValType])
Expand source code
class FuncType:
    def __init__(self, params: List[ValType], results: List[ValType]):
        for param in params:
            if not isinstance(param, ValType):
                raise TypeError("expected ValType")
        for result in results:
            if not isinstance(result, ValType):
                raise TypeError("expected ValType")

        params_ffi = ffi.wasm_valtype_vec_t()
        ffi.wasm_valtype_vec_new_uninitialized(byref(params_ffi), len(params))

        results_ffi = ffi.wasm_valtype_vec_t()
        for i, param in enumerate(params):
            params_ffi.data[i] = take_owned_valtype(param)

        ffi.wasm_valtype_vec_new_uninitialized(
            byref(results_ffi), len(results))
        for i, result in enumerate(results):
            results_ffi.data[i] = take_owned_valtype(result)
        ptr = ffi.wasm_functype_new(byref(params_ffi), byref(results_ffi))
        if not ptr:
            raise WasmtimeError("failed to allocate FuncType")
        self._ptr = ptr
        self._owner = None

    @classmethod
    def _from_ptr(cls, ptr: "pointer[ffi.wasm_functype_t]", owner: Optional[Any]) -> "FuncType":
        ty: "FuncType" = cls.__new__(cls)
        if not isinstance(ptr, POINTER(ffi.wasm_functype_t)):
            raise TypeError("wrong pointer type")
        ty._ptr = ptr
        ty._owner = owner
        return ty

    @property
    def params(self) -> List["ValType"]:
        """
        Returns the list of parameter types for this function type
        """

        ptr = ffi.wasm_functype_params(self._ptr)
        return ValType._from_list(ptr, self)

    @property
    def results(self) -> List["ValType"]:
        """
        Returns the list of result types for this function type
        """

        ptr = ffi.wasm_functype_results(self._ptr)
        return ValType._from_list(ptr, self)

    def _as_extern(self) -> "pointer[ffi.wasm_externtype_t]":
        return ffi.wasm_functype_as_externtype_const(self._ptr)

    def __del__(self) -> None:
        if hasattr(self, '_owner') and self._owner is None:
            ffi.wasm_functype_delete(self._ptr)

Instance variables

var params : List[wasmtime._types.ValType]

Returns the list of parameter types for this function type

Expand source code
@property
def params(self) -> List["ValType"]:
    """
    Returns the list of parameter types for this function type
    """

    ptr = ffi.wasm_functype_params(self._ptr)
    return ValType._from_list(ptr, self)
var results : List[wasmtime._types.ValType]

Returns the list of result types for this function type

Expand source code
@property
def results(self) -> List["ValType"]:
    """
    Returns the list of result types for this function type
    """

    ptr = ffi.wasm_functype_results(self._ptr)
    return ValType._from_list(ptr, self)
class Global (store: Union[wasmtime._store.Store, ForwardRef('Caller')], ty: wasmtime._types.GlobalType, val: Union[wasmtime._value.Val, int, float, ForwardRef(None), ForwardRef('Func'), Any])
Expand source code
class Global:
    _global: ffi.wasmtime_global_t

    def __init__(self, store: Storelike, ty: GlobalType, val: IntoVal):
        if not isinstance(ty, GlobalType):
            raise TypeError("expected a GlobalType")
        val = Val._convert(ty.content, val)
        global_ = ffi.wasmtime_global_t()
        error = ffi.wasmtime_global_new(
            store._context,
            ty._ptr,
            byref(val._unwrap_raw()),
            byref(global_))
        if error:
            raise WasmtimeError._from_ptr(error)
        self._global = global_

    @classmethod
    def _from_raw(cls, global_: ffi.wasmtime_global_t) -> "Global":
        ty: "Global" = cls.__new__(cls)
        ty._global = global_
        return ty

    def type(self, store: Storelike) -> GlobalType:
        """
        Gets the type of this global as a `GlobalType`
        """

        ptr = ffi.wasmtime_global_type(store._context, byref(self._global))
        return GlobalType._from_ptr(ptr, None)

    def value(self, store: Storelike) -> IntoVal:
        """
        Gets the current value of this global

        Returns a native python type
        """
        raw = ffi.wasmtime_val_t()
        ffi.wasmtime_global_get(store._context, byref(self._global), byref(raw))
        val = Val(raw)
        if val.value:
            return val.value
        else:
            return val

    def set_value(self, store: Storelike, val: IntoVal) -> None:
        """
        Sets the value of this global to a new value
        """
        val = Val._convert(self.type(store).content, val)
        error = ffi.wasmtime_global_set(store._context, byref(self._global), byref(val._unwrap_raw()))
        if error:
            raise WasmtimeError._from_ptr(error)

    def _as_extern(self) -> ffi.wasmtime_extern_t:
        union = ffi.wasmtime_extern_union(global_=self._global)
        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_GLOBAL, union)

Methods

def set_value(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], val: Union[wasmtime._value.Val, int, float, ForwardRef(None), ForwardRef('Func'), Any])

Sets the value of this global to a new value

Expand source code
def set_value(self, store: Storelike, val: IntoVal) -> None:
    """
    Sets the value of this global to a new value
    """
    val = Val._convert(self.type(store).content, val)
    error = ffi.wasmtime_global_set(store._context, byref(self._global), byref(val._unwrap_raw()))
    if error:
        raise WasmtimeError._from_ptr(error)
def type(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> wasmtime._types.GlobalType

Gets the type of this global as a GlobalType

Expand source code
def type(self, store: Storelike) -> GlobalType:
    """
    Gets the type of this global as a `GlobalType`
    """

    ptr = ffi.wasmtime_global_type(store._context, byref(self._global))
    return GlobalType._from_ptr(ptr, None)
def value(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> Union[wasmtime._value.Val, int, float, ForwardRef(None), Func, Any]

Gets the current value of this global

Returns a native python type

Expand source code
def value(self, store: Storelike) -> IntoVal:
    """
    Gets the current value of this global

    Returns a native python type
    """
    raw = ffi.wasmtime_val_t()
    ffi.wasmtime_global_get(store._context, byref(self._global), byref(raw))
    val = Val(raw)
    if val.value:
        return val.value
    else:
        return val
class GlobalType (valtype: wasmtime._types.ValType, mutable: bool)
Expand source code
class GlobalType:
    def __init__(self, valtype: ValType, mutable: bool):
        if mutable:
            mutability = ffi.WASM_VAR
        else:
            mutability = ffi.WASM_CONST
        type_ptr = take_owned_valtype(valtype)
        ptr = ffi.wasm_globaltype_new(type_ptr, mutability)
        if ptr == 0:
            raise WasmtimeError("failed to allocate GlobalType")
        self._ptr = ptr
        self._owner = None

    @classmethod
    def _from_ptr(cls, ptr: "pointer[ffi.wasm_globaltype_t]", owner: Optional[Any]) -> "GlobalType":
        ty: "GlobalType" = cls.__new__(cls)
        if not isinstance(ptr, POINTER(ffi.wasm_globaltype_t)):
            raise TypeError("wrong pointer type")
        ty._ptr = ptr
        ty._owner = owner
        return ty

    @property
    def content(self) -> ValType:
        """
        Returns the type this global contains
        """

        ptr = ffi.wasm_globaltype_content(self._ptr)
        return ValType._from_ptr(ptr, self)

    @property
    def mutable(self) -> bool:
        """
        Returns whether this global is mutable or not
        """
        val = ffi.wasm_globaltype_mutability(self._ptr)
        return val == ffi.WASM_VAR.value

    def _as_extern(self) -> "pointer[ffi.wasm_externtype_t]":
        return ffi.wasm_globaltype_as_externtype_const(self._ptr)

    def __del__(self) -> None:
        if hasattr(self, '_owner') and self._owner is None:
            ffi.wasm_globaltype_delete(self._ptr)

Instance variables

var content : wasmtime._types.ValType

Returns the type this global contains

Expand source code
@property
def content(self) -> ValType:
    """
    Returns the type this global contains
    """

    ptr = ffi.wasm_globaltype_content(self._ptr)
    return ValType._from_ptr(ptr, self)
var mutable : bool

Returns whether this global is mutable or not

Expand source code
@property
def mutable(self) -> bool:
    """
    Returns whether this global is mutable or not
    """
    val = ffi.wasm_globaltype_mutability(self._ptr)
    return val == ffi.WASM_VAR.value
class ImportType
Expand source code
class ImportType:
    _ptr: "pointer[ffi.wasm_importtype_t]"
    _owner: Optional[Any]

    @classmethod
    def _from_ptr(cls, ptr: "pointer[ffi.wasm_importtype_t]", owner: Optional[Any]) -> "ImportType":
        ty: "ImportType" = cls.__new__(cls)
        if not isinstance(ptr, POINTER(ffi.wasm_importtype_t)):
            raise TypeError("wrong pointer type")
        ty._ptr = ptr
        ty._owner = owner
        return ty

    @property
    def module(self) -> str:
        """
        Returns the module this import type refers to
        """

        return ffi.to_str(ffi.wasm_importtype_module(self._ptr).contents)

    @property
    def name(self) -> Optional[str]:
        """
        Returns the name in the modulethis import type refers toa.

        Note that `None` may be returned for the module linking proposal where
        the field name is optional.
        """
        ptr = ffi.wasm_importtype_name(self._ptr)
        if ptr:
            return ffi.to_str(ptr.contents)
        return None

    @property
    def type(self) -> "AsExternType":
        """
        Returns the type that this import refers to
        """
        ptr = ffi.wasm_importtype_type(self._ptr)
        return wrap_externtype(ptr, self._owner or self)

    def __del__(self) -> None:
        if self._owner is None:
            ffi.wasm_importtype_delete(self._ptr)

Instance variables

var module : str

Returns the module this import type refers to

Expand source code
@property
def module(self) -> str:
    """
    Returns the module this import type refers to
    """

    return ffi.to_str(ffi.wasm_importtype_module(self._ptr).contents)
var name : Optional[str]

Returns the name in the modulethis import type refers toa.

Note that None may be returned for the module linking proposal where the field name is optional.

Expand source code
@property
def name(self) -> Optional[str]:
    """
    Returns the name in the modulethis import type refers toa.

    Note that `None` may be returned for the module linking proposal where
    the field name is optional.
    """
    ptr = ffi.wasm_importtype_name(self._ptr)
    if ptr:
        return ffi.to_str(ptr.contents)
    return None
var type : Union[wasmtime._types.FuncType, wasmtime._types.TableType, wasmtime._types.MemoryType, wasmtime._types.GlobalType, wasmtime._types.InstanceType, wasmtime._types.ModuleType]

Returns the type that this import refers to

Expand source code
@property
def type(self) -> "AsExternType":
    """
    Returns the type that this import refers to
    """
    ptr = ffi.wasm_importtype_type(self._ptr)
    return wrap_externtype(ptr, self._owner or self)
class Instance (store: Union[wasmtime._store.Store, ForwardRef('Caller')], module: wasmtime._module.Module, imports: Sequence[Union[ForwardRef('Func'), ForwardRef('Table'), ForwardRef('Memory'), ForwardRef('Global'), ForwardRef('Instance'), ForwardRef('Module')]])

Creates a new instance by instantiating the module given with the imports into the store provided.

The store must have type Store, the module must have type Module, and the imports must be an iterable of external values, either Extern, Func, Table, Memory, or Global.

Raises an error if instantiation fails (e.g. linking or trap) and otherwise initializes the new instance.

Expand source code
class Instance:
    _instance: ffi.wasmtime_instance_t
    _exports: Optional["InstanceExports"]

    def __init__(self, store: Storelike, module: Module, imports: Sequence[AsExtern]):
        """
        Creates a new instance by instantiating the `module` given with the
        `imports` into the `store` provided.

        The `store` must have type `Store`, the `module` must have type
        `Module`, and the `imports` must be an iterable of external values,
        either `Extern`, `Func`, `Table`, `Memory`, or `Global`.

        Raises an error if instantiation fails (e.g. linking or trap) and
        otherwise initializes the new instance.
        """

        imports_ptr = (ffi.wasmtime_extern_t * len(imports))()
        for i, val in enumerate(imports):
            imports_ptr[i] = get_extern_ptr(val)

        instance = ffi.wasmtime_instance_t()
        trap = POINTER(ffi.wasm_trap_t)()
        with enter_wasm(store) as trap:
            error = ffi.wasmtime_instance_new(
                store._context,
                module._ptr,
                imports_ptr,
                len(imports),
                byref(instance),
                trap)
            if error:
                raise WasmtimeError._from_ptr(error)
        self._instance = instance
        self._exports = None

    @classmethod
    def _from_raw(cls, instance: ffi.wasmtime_instance_t) -> "Instance":
        ty: "Instance" = cls.__new__(cls)
        ty._exports = None
        ty._instance = instance
        return ty

    def type(self, store: Store) -> InstanceType:
        """
        Gets the type of this instance as an `InstanceType`
        """

        ptr = ffi.wasmtime_instance_type(store._context, byref(self._instance))
        return InstanceType._from_ptr(ptr, None)

    def exports(self, store: Storelike) -> "InstanceExports":
        """
        Returns the exports of this module

        The returned type can be indexed both with integers and with strings for
        names of exports.
        """
        if self._exports is None:
            self._exports = InstanceExports(store, self)
        return self._exports

    def _as_extern(self) -> ffi.wasmtime_extern_t:
        union = ffi.wasmtime_extern_union(instance=self._instance)
        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_INSTANCE, union)

Methods

def exports(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> wasmtime._instance.InstanceExports

Returns the exports of this module

The returned type can be indexed both with integers and with strings for names of exports.

Expand source code
def exports(self, store: Storelike) -> "InstanceExports":
    """
    Returns the exports of this module

    The returned type can be indexed both with integers and with strings for
    names of exports.
    """
    if self._exports is None:
        self._exports = InstanceExports(store, self)
    return self._exports
def type(self, store: wasmtime._store.Store) ‑> wasmtime._types.InstanceType

Gets the type of this instance as an InstanceType

Expand source code
def type(self, store: Store) -> InstanceType:
    """
    Gets the type of this instance as an `InstanceType`
    """

    ptr = ffi.wasmtime_instance_type(store._context, byref(self._instance))
    return InstanceType._from_ptr(ptr, None)
class Limits (min: int, max: Optional[int])
Expand source code
class Limits:
    def __init__(self, min: int, max: Optional[int]):
        self.min = min
        self.max = max

    def __ffi__(self) -> ffi.wasm_limits_t:
        max = self.max
        if max is None:
            max = 0xffffffff
        return ffi.wasm_limits_t(self.min, max)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Limits):
            return False
        return self.min == other.min and self.max == other.max

    @classmethod
    def _from_ffi(cls, val: 'pointer[ffi.wasm_limits_t]') -> "Limits":
        min = val.contents.min
        max = val.contents.max
        if max == 0xffffffff:
            return Limits(min, None)
        return Limits(min, max)
class Linker (engine: wasmtime._engine.Engine)

Creates a new linker ready to instantiate modules within the store provided.

Expand source code
class Linker:
    engine: Engine

    def __init__(self, engine: Engine):
        """
        Creates a new linker ready to instantiate modules within the store
        provided.
        """
        self._ptr = ffi.wasmtime_linker_new(engine._ptr)
        self.engine = engine

    @setter_property
    def allow_shadowing(self, allow: bool) -> None:
        """
        Configures whether definitions are allowed to shadow one another within
        this linker
        """
        if not isinstance(allow, bool):
            raise TypeError("expected a boolean")
        ffi.wasmtime_linker_allow_shadowing(self._ptr, allow)

    def define(self, module: str, name: str, item: AsExtern) -> None:
        """
        Defines a new item, by name, in this linker.

        This method will add a new definition to this linker. The `module` nad
        `name` provided are what to name the `item` within the linker.

        This function will raise an error if `item` comes from the wrong store
        or if shadowing is disallowed and the module/name pair has already been
        defined.
        """
        raw_item = get_extern_ptr(item)
        module_bytes = module.encode('utf-8')
        module_buf = create_string_buffer(module_bytes)
        name_bytes = name.encode('utf-8')
        name_buf = create_string_buffer(name_bytes)
        error = ffi.wasmtime_linker_define(
            self._ptr,
            module_buf,
            len(module_bytes),
            name_buf,
            len(name_bytes),
            byref(raw_item))
        if error:
            raise WasmtimeError._from_ptr(error)

    def define_func(self, module: str, name: str, ty: FuncType, func: Callable, access_caller: bool = False) -> None:
        """
        Defines a new function, by name, in this linker.

        This method is similar to `define` except that you can directly define a
        function without creating a `Func` itself. This enables
        `Store`-independent functions to be inserted into this linker, meaning
        the linker can be used to instantiate modules in multiple stores.
        """
        module_bytes = module.encode('utf-8')
        module_buf = create_string_buffer(module_bytes)
        name_bytes = name.encode('utf-8')
        name_buf = create_string_buffer(name_bytes)
        if not isinstance(ty, FuncType):
            raise TypeError("expected a FuncType")
        idx = FUNCTIONS.allocate((func, ty.results, access_caller))
        error = ffi.wasmtime_linker_define_func(
            self._ptr,
            module_buf,
            len(module_bytes),
            name_buf,
            len(name_bytes),
            ty._ptr,
            trampoline,
            idx,
            finalize)
        if error:
            raise WasmtimeError._from_ptr(error)

    def define_instance(self, store: Storelike, name: str, instance: Instance) -> None:
        """
        Convenience wrapper to define an entire instance in this linker.

        This function will `define` eaech of the exports on the instance into
        this linker, using the name provided as the module name and the export's
        own name as the field name.

        This function will raise an error if `instance` comes from the wrong
        store or if shadowing is disallowed and a name was previously defined.
        """
        if not isinstance(instance, Instance):
            raise TypeError("expected an `Instance`")
        name_bytes = name.encode('utf8')
        name_buf = create_string_buffer(name_bytes)
        error = ffi.wasmtime_linker_define_instance(self._ptr,
                                                    store._context,
                                                    name_buf,
                                                    len(name_bytes),
                                                    byref(instance._instance))
        if error:
            raise WasmtimeError._from_ptr(error)

    def define_wasi(self) -> None:
        """
        Defines a WASI instance in this linker.

        The instance provided has been previously constructed and this method
        will define all the appropriate imports and their names into this linker
        to assist with instantiating modules that use WASI.

        This function will raise an error if shadowing is disallowed and a name
        was previously defined.
        """
        error = ffi.wasmtime_linker_define_wasi(self._ptr)
        if error:
            raise WasmtimeError._from_ptr(error)

    def define_module(self, store: Storelike, name: str, module: Module) -> None:
        """
        Defines automatic instantiations of the provided module in this linker.

        The `module` provided is defined under `name` with automatic
        instantiations which respect WASI Commands and Reactors.

        For more information see the Rust documentation at
        https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.module.

        This method will throw an error if shadowing is disallowed and an item
        has previously been defined.
        """
        if not isinstance(module, Module):
            raise TypeError("expected a `Module`")
        name_bytes = name.encode('utf-8')
        name_buf = create_string_buffer(name_bytes)
        error = ffi.wasmtime_linker_module(self._ptr, store._context, name_buf, len(name_bytes), module._ptr)
        if error:
            raise WasmtimeError._from_ptr(error)

    def instantiate(self, store: Storelike, module: Module) -> Instance:
        """
        Instantiates a module using this linker's defined set of names.

        This method will attempt to satisfy all the imports of the `module`
        provided with the names defined within this linker. If all names are
        defined then the module is instantiated.

        Raises an error if an import of `module` hasn't been defined in this
        linker or if a trap happens while instantiating the instance.
        """
        trap = POINTER(ffi.wasm_trap_t)()
        instance = ffi.wasmtime_instance_t()
        with enter_wasm(store) as trap:
            error = ffi.wasmtime_linker_instantiate(
                self._ptr, store._context, module._ptr, byref(instance), trap)
            if error:
                raise WasmtimeError._from_ptr(error)
        return Instance._from_raw(instance)

    def get_default(self, store: Storelike, name: str) -> Func:
        """
        Gets the default export for the named module in this linker.

        For more information on this see the Rust documentation at
        https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.get_default.

        Raises an error if the default export wasn't present.
        """
        name_bytes = name.encode('utf-8')
        name_buf = create_string_buffer(name_bytes)
        func = ffi.wasmtime_func_t()
        error = ffi.wasmtime_linker_get_default(self._ptr, store._context,
                                                name_buf, len(name_bytes), byref(func))
        if error:
            raise WasmtimeError._from_ptr(error)
        return Func._from_raw(func)

    def get(self, store: Storelike, module: str, name: str) -> AsExtern:
        """
        Gets a singular item defined in this linker.

        Raises an error if this item hasn't been defined or if the item has been
        defined twice with different types.
        """
        module_bytes = module.encode('utf-8')
        module_buf = create_string_buffer(module_bytes)
        name_bytes = name.encode('utf-8')
        name_buf = create_string_buffer(name_bytes)
        item = ffi.wasmtime_extern_t()
        ok = ffi.wasmtime_linker_get(self._ptr, store._context,
                                     module_buf, len(module_bytes),
                                     name_buf, len(name_bytes),
                                     byref(item))
        if ok:
            return wrap_extern(item)
        raise WasmtimeError("item not defined in linker")

    def __del__(self) -> None:
        if hasattr(self, '_ptr'):
            ffi.wasmtime_linker_delete(self._ptr)

Class variables

var engine : wasmtime._engine.Engine

Instance variables

var allow_shadowing

Configures whether definitions are allowed to shadow one another within this linker

Note that this field can only be set, it cannot be read

Methods

def define(self, module: str, name: str, item: Union[ForwardRef('Func'), ForwardRef('Table'), ForwardRef('Memory'), ForwardRef('Global'), ForwardRef('Instance'), ForwardRef('Module')])

Defines a new item, by name, in this linker.

This method will add a new definition to this linker. The module nad name provided are what to name the item within the linker.

This function will raise an error if item comes from the wrong store or if shadowing is disallowed and the module/name pair has already been defined.

Expand source code
def define(self, module: str, name: str, item: AsExtern) -> None:
    """
    Defines a new item, by name, in this linker.

    This method will add a new definition to this linker. The `module` nad
    `name` provided are what to name the `item` within the linker.

    This function will raise an error if `item` comes from the wrong store
    or if shadowing is disallowed and the module/name pair has already been
    defined.
    """
    raw_item = get_extern_ptr(item)
    module_bytes = module.encode('utf-8')
    module_buf = create_string_buffer(module_bytes)
    name_bytes = name.encode('utf-8')
    name_buf = create_string_buffer(name_bytes)
    error = ffi.wasmtime_linker_define(
        self._ptr,
        module_buf,
        len(module_bytes),
        name_buf,
        len(name_bytes),
        byref(raw_item))
    if error:
        raise WasmtimeError._from_ptr(error)
def define_func(self, module: str, name: str, ty: wasmtime._types.FuncType, func: Callable, access_caller: bool = False) ‑> None

Defines a new function, by name, in this linker.

This method is similar to define except that you can directly define a function without creating a Func itself. This enables Store-independent functions to be inserted into this linker, meaning the linker can be used to instantiate modules in multiple stores.

Expand source code
def define_func(self, module: str, name: str, ty: FuncType, func: Callable, access_caller: bool = False) -> None:
    """
    Defines a new function, by name, in this linker.

    This method is similar to `define` except that you can directly define a
    function without creating a `Func` itself. This enables
    `Store`-independent functions to be inserted into this linker, meaning
    the linker can be used to instantiate modules in multiple stores.
    """
    module_bytes = module.encode('utf-8')
    module_buf = create_string_buffer(module_bytes)
    name_bytes = name.encode('utf-8')
    name_buf = create_string_buffer(name_bytes)
    if not isinstance(ty, FuncType):
        raise TypeError("expected a FuncType")
    idx = FUNCTIONS.allocate((func, ty.results, access_caller))
    error = ffi.wasmtime_linker_define_func(
        self._ptr,
        module_buf,
        len(module_bytes),
        name_buf,
        len(name_bytes),
        ty._ptr,
        trampoline,
        idx,
        finalize)
    if error:
        raise WasmtimeError._from_ptr(error)
def define_instance(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], name: str, instance: wasmtime._instance.Instance) ‑> None

Convenience wrapper to define an entire instance in this linker.

This function will define eaech of the exports on the instance into this linker, using the name provided as the module name and the export's own name as the field name.

This function will raise an error if instance comes from the wrong store or if shadowing is disallowed and a name was previously defined.

Expand source code
def define_instance(self, store: Storelike, name: str, instance: Instance) -> None:
    """
    Convenience wrapper to define an entire instance in this linker.

    This function will `define` eaech of the exports on the instance into
    this linker, using the name provided as the module name and the export's
    own name as the field name.

    This function will raise an error if `instance` comes from the wrong
    store or if shadowing is disallowed and a name was previously defined.
    """
    if not isinstance(instance, Instance):
        raise TypeError("expected an `Instance`")
    name_bytes = name.encode('utf8')
    name_buf = create_string_buffer(name_bytes)
    error = ffi.wasmtime_linker_define_instance(self._ptr,
                                                store._context,
                                                name_buf,
                                                len(name_bytes),
                                                byref(instance._instance))
    if error:
        raise WasmtimeError._from_ptr(error)
def define_module(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], name: str, module: wasmtime._module.Module) ‑> None

Defines automatic instantiations of the provided module in this linker.

The module provided is defined under name with automatic instantiations which respect WASI Commands and Reactors.

For more information see the Rust documentation at https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.module.

This method will throw an error if shadowing is disallowed and an item has previously been defined.

Expand source code
def define_module(self, store: Storelike, name: str, module: Module) -> None:
    """
    Defines automatic instantiations of the provided module in this linker.

    The `module` provided is defined under `name` with automatic
    instantiations which respect WASI Commands and Reactors.

    For more information see the Rust documentation at
    https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.module.

    This method will throw an error if shadowing is disallowed and an item
    has previously been defined.
    """
    if not isinstance(module, Module):
        raise TypeError("expected a `Module`")
    name_bytes = name.encode('utf-8')
    name_buf = create_string_buffer(name_bytes)
    error = ffi.wasmtime_linker_module(self._ptr, store._context, name_buf, len(name_bytes), module._ptr)
    if error:
        raise WasmtimeError._from_ptr(error)
def define_wasi(self) ‑> None

Defines a WASI instance in this linker.

The instance provided has been previously constructed and this method will define all the appropriate imports and their names into this linker to assist with instantiating modules that use WASI.

This function will raise an error if shadowing is disallowed and a name was previously defined.

Expand source code
def define_wasi(self) -> None:
    """
    Defines a WASI instance in this linker.

    The instance provided has been previously constructed and this method
    will define all the appropriate imports and their names into this linker
    to assist with instantiating modules that use WASI.

    This function will raise an error if shadowing is disallowed and a name
    was previously defined.
    """
    error = ffi.wasmtime_linker_define_wasi(self._ptr)
    if error:
        raise WasmtimeError._from_ptr(error)
def get(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], module: str, name: str) ‑> Union[FuncTableMemoryGlobalInstanceModule]

Gets a singular item defined in this linker.

Raises an error if this item hasn't been defined or if the item has been defined twice with different types.

Expand source code
def get(self, store: Storelike, module: str, name: str) -> AsExtern:
    """
    Gets a singular item defined in this linker.

    Raises an error if this item hasn't been defined or if the item has been
    defined twice with different types.
    """
    module_bytes = module.encode('utf-8')
    module_buf = create_string_buffer(module_bytes)
    name_bytes = name.encode('utf-8')
    name_buf = create_string_buffer(name_bytes)
    item = ffi.wasmtime_extern_t()
    ok = ffi.wasmtime_linker_get(self._ptr, store._context,
                                 module_buf, len(module_bytes),
                                 name_buf, len(name_bytes),
                                 byref(item))
    if ok:
        return wrap_extern(item)
    raise WasmtimeError("item not defined in linker")
def get_default(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], name: str) ‑> wasmtime._func.Func

Gets the default export for the named module in this linker.

For more information on this see the Rust documentation at https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.get_default.

Raises an error if the default export wasn't present.

Expand source code
def get_default(self, store: Storelike, name: str) -> Func:
    """
    Gets the default export for the named module in this linker.

    For more information on this see the Rust documentation at
    https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.get_default.

    Raises an error if the default export wasn't present.
    """
    name_bytes = name.encode('utf-8')
    name_buf = create_string_buffer(name_bytes)
    func = ffi.wasmtime_func_t()
    error = ffi.wasmtime_linker_get_default(self._ptr, store._context,
                                            name_buf, len(name_bytes), byref(func))
    if error:
        raise WasmtimeError._from_ptr(error)
    return Func._from_raw(func)
def instantiate(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], module: wasmtime._module.Module) ‑> wasmtime._instance.Instance

Instantiates a module using this linker's defined set of names.

This method will attempt to satisfy all the imports of the module provided with the names defined within this linker. If all names are defined then the module is instantiated.

Raises an error if an import of module hasn't been defined in this linker or if a trap happens while instantiating the instance.

Expand source code
def instantiate(self, store: Storelike, module: Module) -> Instance:
    """
    Instantiates a module using this linker's defined set of names.

    This method will attempt to satisfy all the imports of the `module`
    provided with the names defined within this linker. If all names are
    defined then the module is instantiated.

    Raises an error if an import of `module` hasn't been defined in this
    linker or if a trap happens while instantiating the instance.
    """
    trap = POINTER(ffi.wasm_trap_t)()
    instance = ffi.wasmtime_instance_t()
    with enter_wasm(store) as trap:
        error = ffi.wasmtime_linker_instantiate(
            self._ptr, store._context, module._ptr, byref(instance), trap)
        if error:
            raise WasmtimeError._from_ptr(error)
    return Instance._from_raw(instance)
class Memory (store: Union[wasmtime._store.Store, ForwardRef('Caller')], ty: wasmtime._types.MemoryType)

Creates a new memory in store with the given ty

Expand source code
class Memory:
    _memory: ffi.wasmtime_memory_t

    def __init__(self, store: Storelike, ty: MemoryType):
        """
        Creates a new memory in `store` with the given `ty`
        """

        mem = ffi.wasmtime_memory_t()
        error = ffi.wasmtime_memory_new(store._context, ty._ptr, byref(mem))
        if error:
            raise WasmtimeError._from_ptr(error)
        self._memory = mem

    @classmethod
    def _from_raw(cls, mem: ffi.wasmtime_memory_t) -> "Memory":
        ty: "Memory" = cls.__new__(cls)
        ty._memory = mem
        return ty

    def type(self, store: Storelike) -> MemoryType:
        """
        Gets the type of this memory as a `MemoryType`
        """

        ptr = ffi.wasmtime_memory_type(store._context, byref(self._memory))
        return MemoryType._from_ptr(ptr, None)

    def grow(self, store: Storelike, delta: int) -> int:
        """
        Grows this memory by the given number of pages
        """

        if delta < 0:
            raise WasmtimeError("cannot grow by negative amount")
        prev = ffi.c_uint64(0)
        error = ffi.wasmtime_memory_grow(store._context, byref(self._memory), delta, byref(prev))
        if error:
            raise WasmtimeError._from_ptr(error)
        return prev.value

    def size(self, store: Storelike) -> int:
        """
        Returns the size, in WebAssembly pages, of this memory.
        """

        return ffi.wasmtime_memory_size(store._context, byref(self._memory))

    def data_ptr(self, store: Storelike) -> "pointer[c_ubyte]":
        """
        Returns the raw pointer in memory where this wasm memory lives.

        Remember that all accesses to wasm memory should be bounds-checked
        against the `data_len` method.
        """
        return ffi.wasmtime_memory_data(store._context, byref(self._memory))

    def data_len(self, store: Storelike) -> int:
        """
        Returns the raw byte length of this memory.
        """

        return ffi.wasmtime_memory_data_size(store._context, byref(self._memory))

    def _as_extern(self) -> ffi.wasmtime_extern_t:
        union = ffi.wasmtime_extern_union(memory=self._memory)
        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_MEMORY, union)

Methods

def data_len(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> int

Returns the raw byte length of this memory.

Expand source code
def data_len(self, store: Storelike) -> int:
    """
    Returns the raw byte length of this memory.
    """

    return ffi.wasmtime_memory_data_size(store._context, byref(self._memory))
def data_ptr(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> pointer[c_ubyte]

Returns the raw pointer in memory where this wasm memory lives.

Remember that all accesses to wasm memory should be bounds-checked against the data_len method.

Expand source code
def data_ptr(self, store: Storelike) -> "pointer[c_ubyte]":
    """
    Returns the raw pointer in memory where this wasm memory lives.

    Remember that all accesses to wasm memory should be bounds-checked
    against the `data_len` method.
    """
    return ffi.wasmtime_memory_data(store._context, byref(self._memory))
def grow(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], delta: int) ‑> int

Grows this memory by the given number of pages

Expand source code
def grow(self, store: Storelike, delta: int) -> int:
    """
    Grows this memory by the given number of pages
    """

    if delta < 0:
        raise WasmtimeError("cannot grow by negative amount")
    prev = ffi.c_uint64(0)
    error = ffi.wasmtime_memory_grow(store._context, byref(self._memory), delta, byref(prev))
    if error:
        raise WasmtimeError._from_ptr(error)
    return prev.value
def size(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> int

Returns the size, in WebAssembly pages, of this memory.

Expand source code
def size(self, store: Storelike) -> int:
    """
    Returns the size, in WebAssembly pages, of this memory.
    """

    return ffi.wasmtime_memory_size(store._context, byref(self._memory))
def type(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> wasmtime._types.MemoryType

Gets the type of this memory as a MemoryType

Expand source code
def type(self, store: Storelike) -> MemoryType:
    """
    Gets the type of this memory as a `MemoryType`
    """

    ptr = ffi.wasmtime_memory_type(store._context, byref(self._memory))
    return MemoryType._from_ptr(ptr, None)
class MemoryType (limits: wasmtime._types.Limits, is_64: bool = False)
Expand source code
class MemoryType:
    def __init__(self, limits: Limits, is_64: bool = False):
        if not isinstance(limits, Limits):
            raise TypeError("expected Limits")
        if is_64:
            maximum = 0x10000000000000000
        else:
            maximum = 0x100000000
        if limits.min >= maximum:
            raise WasmtimeError("minimum size too large")
        if limits.max and limits.max >= maximum:
            raise WasmtimeError("maximum size too large")
        ptr = ffi.wasmtime_memorytype_new(limits.min,
                                          limits.max is not None,
                                          limits.max if limits.max else 0,
                                          is_64)
        if not ptr:
            raise WasmtimeError("failed to allocate MemoryType")
        self._ptr = ptr
        self._owner = None

    @classmethod
    def _from_ptr(cls, ptr: "pointer[ffi.wasm_memorytype_t]", owner: Optional[Any]) -> "MemoryType":
        ty: "MemoryType" = cls.__new__(cls)
        if not isinstance(ptr, POINTER(ffi.wasm_memorytype_t)):
            raise TypeError("wrong pointer type")
        ty._ptr = ptr
        ty._owner = owner
        return ty

    @property
    def limits(self) -> Limits:
        """
        Returns the limits on the size of this table
        """
        minimum = ffi.wasmtime_memorytype_minimum(self._ptr)
        maximum = ffi.c_uint64(0)
        has_max = ffi.wasmtime_memorytype_maximum(self._ptr, byref(maximum))
        return Limits(minimum, maximum.value if has_max else None)

    @property
    def is_64(self) -> bool:
        """
        Returns whether or not this is a 64-bit memory
        """
        return ffi.wasmtime_memorytype_is64(self._ptr)

    def _as_extern(self) -> "pointer[ffi.wasm_externtype_t]":
        return ffi.wasm_memorytype_as_externtype_const(self._ptr)

    def __del__(self) -> None:
        if hasattr(self, '_owner') and self._owner is None:
            ffi.wasm_memorytype_delete(self._ptr)

Instance variables

var is_64 : bool

Returns whether or not this is a 64-bit memory

Expand source code
@property
def is_64(self) -> bool:
    """
    Returns whether or not this is a 64-bit memory
    """
    return ffi.wasmtime_memorytype_is64(self._ptr)
var limits : wasmtime._types.Limits

Returns the limits on the size of this table

Expand source code
@property
def limits(self) -> Limits:
    """
    Returns the limits on the size of this table
    """
    minimum = ffi.wasmtime_memorytype_minimum(self._ptr)
    maximum = ffi.c_uint64(0)
    has_max = ffi.wasmtime_memorytype_maximum(self._ptr, byref(maximum))
    return Limits(minimum, maximum.value if has_max else None)
class Module (engine: wasmtime._engine.Engine, wasm: Union[str, bytes])
Expand source code
class Module:
    @classmethod
    def from_file(cls, engine: Engine, path: str) -> "Module":
        """
        Compiles and creates a new `Module` by reading the file at `path` and
        then delegating to the `Module` constructor.
        """

        with open(path, "rb") as f:
            contents = f.read()
        return cls(engine, contents)

    def __init__(self, engine: Engine, wasm: typing.Union[str, bytes]):
        if not isinstance(engine, Engine):
            raise TypeError("expected an Engine")

        # If this looks like a string, parse it as the text format. Note that
        # in python 2 strings and bytes are basically the same, so we skip this
        # if the first byte in the string is 0, meaning this is actually a wasm
        # module.
        if isinstance(wasm, str) and len(wasm) > 0 and ord(wasm[0]) != 0:
            wasm = wat2wasm(wasm)
        if isinstance(wasm, bytes) and len(wasm) > 0 and wasm[0] != 0:
            wasm = wat2wasm(wasm)

        if not isinstance(wasm, (bytes, bytearray)):
            raise TypeError("expected wasm bytes")

        # TODO: can the copy be avoided here? I can't for the life of me
        # figure this out.
        binary = (c_uint8 * len(wasm)).from_buffer_copy(wasm)
        ptr = POINTER(ffi.wasmtime_module_t)()
        error = ffi.wasmtime_module_new(engine._ptr, binary, len(wasm), byref(ptr))
        if error:
            raise WasmtimeError._from_ptr(error)
        self._ptr = ptr

    @classmethod
    def _from_ptr(cls, ptr: "pointer[ffi.wasmtime_module_t]") -> "Module":
        ty: "Module" = cls.__new__(cls)
        if not isinstance(ptr, POINTER(ffi.wasmtime_module_t)):
            raise TypeError("wrong pointer type")
        ty._ptr = ptr
        return ty

    @classmethod
    def deserialize(cls, engine: Engine, encoded: typing.Union[bytes, bytearray]) -> 'Module':
        """
        Deserializes bytes previously created by `Module.serialize`.

        This constructor for `Module` will deserialize bytes previously created
        by a serialized module. This will only succeed if the bytes were
        previously created by the same version of `wasmtime` as well as the
        same configuration within `Engine`.
        """

        if not isinstance(encoded, (bytes, bytearray)):
            raise TypeError("expected bytes")

        ptr = POINTER(ffi.wasmtime_module_t)()

        # TODO: can the copy be avoided here? I can't for the life of me
        # figure this out.
        error = ffi.wasmtime_module_deserialize(
            engine._ptr,
            (c_uint8 * len(encoded)).from_buffer_copy(encoded),
            len(encoded),
            byref(ptr))
        if error:
            raise WasmtimeError._from_ptr(error)
        ret: "Module" = cls.__new__(cls)
        ret._ptr = ptr
        return ret

    @classmethod
    def deserialize_file(cls, engine: Engine, path: str) -> 'Module':
        """
        Deserializes bytes previously created by `Module.serialize` that are
        stored in a file on the filesystem.

        Otherwise this function is the same as `Module.deserialize`.
        """

        ptr = POINTER(ffi.wasmtime_module_t)()
        path_bytes = path.encode('utf-8')
        error = ffi.wasmtime_module_deserialize_file(
            engine._ptr,
            path_bytes,
            byref(ptr))
        if error:
            raise WasmtimeError._from_ptr(error)
        ret: "Module" = cls.__new__(cls)
        ret._ptr = ptr
        return ret

    @classmethod
    def validate(cls, engine: Engine, wasm: typing.Union[bytes, bytearray]) -> None:
        """
        Validates whether the list of bytes `wasm` provided is a valid
        WebAssembly binary given the configuration in `store`

        Raises a `WasmtimeError` if the wasm isn't valid.
        """

        if not isinstance(wasm, (bytes, bytearray)):
            raise TypeError("expected wasm bytes")

        # TODO: can the copy be avoided here? I can't for the life of me
        # figure this out.
        buf = (c_uint8 * len(wasm)).from_buffer_copy(wasm)
        error = ffi.wasmtime_module_validate(engine._ptr, buf, len(wasm))

        if error:
            raise WasmtimeError._from_ptr(error)

    @property
    def type(self) -> ModuleType:
        """
        Gets the type of this module as a `ModuleType`
        """

        ptr = ffi.wasmtime_module_type(self._ptr)
        return ModuleType._from_ptr(ptr, None)

    @property
    def imports(self) -> typing.List[ImportType]:
        """
        Returns the types of imports that this module has
        """

        return self.type.imports

    @property
    def exports(self) -> typing.List[ExportType]:
        """
        Returns the types of the exports that this module has
        """
        return self.type.exports

    def serialize(self) -> bytearray:
        """
        Serializes this module to a binary representation.

        This method will serialize this module to an in-memory byte array which
        can be cached and later passed to `Module.deserialize` to recreate this
        module.
        """
        raw = ffi.wasm_byte_vec_t()
        err = ffi.wasmtime_module_serialize(self._ptr, byref(raw))
        if err:
            raise WasmtimeError._from_ptr(err)
        ret = ffi.to_bytes(raw)
        ffi.wasm_byte_vec_delete(byref(raw))
        return ret

    def _as_extern(self) -> ffi.wasmtime_extern_t:
        union = ffi.wasmtime_extern_union(module=self._ptr)
        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_MODULE, union)

    def __del__(self) -> None:
        if hasattr(self, '_ptr'):
            ffi.wasmtime_module_delete(self._ptr)

Static methods

def deserialize(engine: wasmtime._engine.Engine, encoded: Union[bytes, bytearray]) ‑> wasmtime._module.Module

Deserializes bytes previously created by Module.serialize().

This constructor for Module will deserialize bytes previously created by a serialized module. This will only succeed if the bytes were previously created by the same version of wasmtime as well as the same configuration within Engine.

Expand source code
@classmethod
def deserialize(cls, engine: Engine, encoded: typing.Union[bytes, bytearray]) -> 'Module':
    """
    Deserializes bytes previously created by `Module.serialize`.

    This constructor for `Module` will deserialize bytes previously created
    by a serialized module. This will only succeed if the bytes were
    previously created by the same version of `wasmtime` as well as the
    same configuration within `Engine`.
    """

    if not isinstance(encoded, (bytes, bytearray)):
        raise TypeError("expected bytes")

    ptr = POINTER(ffi.wasmtime_module_t)()

    # TODO: can the copy be avoided here? I can't for the life of me
    # figure this out.
    error = ffi.wasmtime_module_deserialize(
        engine._ptr,
        (c_uint8 * len(encoded)).from_buffer_copy(encoded),
        len(encoded),
        byref(ptr))
    if error:
        raise WasmtimeError._from_ptr(error)
    ret: "Module" = cls.__new__(cls)
    ret._ptr = ptr
    return ret
def deserialize_file(engine: wasmtime._engine.Engine, path: str) ‑> wasmtime._module.Module

Deserializes bytes previously created by Module.serialize() that are stored in a file on the filesystem.

Otherwise this function is the same as Module.deserialize().

Expand source code
@classmethod
def deserialize_file(cls, engine: Engine, path: str) -> 'Module':
    """
    Deserializes bytes previously created by `Module.serialize` that are
    stored in a file on the filesystem.

    Otherwise this function is the same as `Module.deserialize`.
    """

    ptr = POINTER(ffi.wasmtime_module_t)()
    path_bytes = path.encode('utf-8')
    error = ffi.wasmtime_module_deserialize_file(
        engine._ptr,
        path_bytes,
        byref(ptr))
    if error:
        raise WasmtimeError._from_ptr(error)
    ret: "Module" = cls.__new__(cls)
    ret._ptr = ptr
    return ret
def from_file(engine: wasmtime._engine.Engine, path: str) ‑> wasmtime._module.Module

Compiles and creates a new Module by reading the file at path and then delegating to the Module constructor.

Expand source code
@classmethod
def from_file(cls, engine: Engine, path: str) -> "Module":
    """
    Compiles and creates a new `Module` by reading the file at `path` and
    then delegating to the `Module` constructor.
    """

    with open(path, "rb") as f:
        contents = f.read()
    return cls(engine, contents)
def validate(engine: wasmtime._engine.Engine, wasm: Union[bytes, bytearray]) ‑> None

Validates whether the list of bytes wasm provided is a valid WebAssembly binary given the configuration in store

Raises a WasmtimeError if the wasm isn't valid.

Expand source code
@classmethod
def validate(cls, engine: Engine, wasm: typing.Union[bytes, bytearray]) -> None:
    """
    Validates whether the list of bytes `wasm` provided is a valid
    WebAssembly binary given the configuration in `store`

    Raises a `WasmtimeError` if the wasm isn't valid.
    """

    if not isinstance(wasm, (bytes, bytearray)):
        raise TypeError("expected wasm bytes")

    # TODO: can the copy be avoided here? I can't for the life of me
    # figure this out.
    buf = (c_uint8 * len(wasm)).from_buffer_copy(wasm)
    error = ffi.wasmtime_module_validate(engine._ptr, buf, len(wasm))

    if error:
        raise WasmtimeError._from_ptr(error)

Instance variables

var exports : List[wasmtime._types.ExportType]

Returns the types of the exports that this module has

Expand source code
@property
def exports(self) -> typing.List[ExportType]:
    """
    Returns the types of the exports that this module has
    """
    return self.type.exports
var imports : List[wasmtime._types.ImportType]

Returns the types of imports that this module has

Expand source code
@property
def imports(self) -> typing.List[ImportType]:
    """
    Returns the types of imports that this module has
    """

    return self.type.imports
var type : wasmtime._types.ModuleType

Gets the type of this module as a ModuleType

Expand source code
@property
def type(self) -> ModuleType:
    """
    Gets the type of this module as a `ModuleType`
    """

    ptr = ffi.wasmtime_module_type(self._ptr)
    return ModuleType._from_ptr(ptr, None)

Methods

def serialize(self) ‑> bytearray

Serializes this module to a binary representation.

This method will serialize this module to an in-memory byte array which can be cached and later passed to Module.deserialize() to recreate this module.

Expand source code
def serialize(self) -> bytearray:
    """
    Serializes this module to a binary representation.

    This method will serialize this module to an in-memory byte array which
    can be cached and later passed to `Module.deserialize` to recreate this
    module.
    """
    raw = ffi.wasm_byte_vec_t()
    err = ffi.wasmtime_module_serialize(self._ptr, byref(raw))
    if err:
        raise WasmtimeError._from_ptr(err)
    ret = ffi.to_bytes(raw)
    ffi.wasm_byte_vec_delete(byref(raw))
    return ret
class Store (engine: wasmtime._engine.Engine = None, data: Optional[Any] = None)
Expand source code
class Store:
    _ptr: "pointer[ffi.wasmtime_store_t]"
    _context: "pointer[ffi.wasmtime_context_t]"

    def __init__(self, engine: Engine = None, data: typing.Optional[typing.Any] = None):

        if engine is None:
            engine = Engine()
        elif not isinstance(engine, Engine):
            raise TypeError("expected an Engine")
        data_id = ffi.c_void_p(0)
        finalize = cast(0, CFUNCTYPE(None, c_void_p))
        if data:
            data_id = value._intern(data)
            finalize = value._externref_finalizer
        self._ptr = ffi.wasmtime_store_new(engine._ptr, data_id, finalize)
        self._context = ffi.wasmtime_store_context(self._ptr)
        self.engine = engine

    def data(self) -> typing.Optional[typing.Any]:
        """
        TODO
        """
        data = ffi.wasmtime_context_get_data(self._context)
        if data:
            return value._unintern(data)
        else:
            return None

    def interrupt_handle(self) -> "InterruptHandle":
        """
        Creates a new interrupt handle through which execution of wasm can be
        interrupted.

        Raises a `WasmtimeError` if this store's configuration has not been
        configured to enable interruption.

        For more information about this be sure to consult the Rust documentation:
        https://bytecodealliance.github.io/wasmtime/api/wasmtime/struct.Store.html#method.interrupt_handle
        """

        return InterruptHandle(self)

    def gc(self) -> None:
        """
        Runs a GC over `externref` values that have been passed into this Store,
        cleaning out anything that is no longer referenced.

        This is not required to be run manually, but can be done so if you'd
        like more precise control over when unreferenced `externref` values are
        deallocated.
        """
        ffi.wasmtime_context_gc(self._context)

    def add_fuel(self, fuel: int) -> None:
        """
        Adds the specified amount of fuel into this store.

        This is only relevant when `Config.consume_fuel` is configured.

        This is a required call to ensure that the store has fuel to
        execute WebAssembly since otherwise stores start with zero fuel.

        Raises a `WasmtimeError` if this store's configuration is not configured
        to consume fuel.
        """
        err = ffi.wasmtime_context_add_fuel(self._context, fuel)
        if err:
            raise WasmtimeError._from_ptr(err)

    def fuel_consumed(self) -> int:
        """
        Returns the amount of fuel consumed by this `Store` so far.

        Raises a `WasmtimeError` if this store's configuration is not configured
        to consume fuel.
        """
        fuel = c_uint64(0)
        ok = ffi.wasmtime_context_fuel_consumed(self._context, byref(fuel))
        if ok:
            return fuel.value
        raise WasmtimeError("fuel is not enabled in this store's configuration")

    def consume_fuel(self, fuel: int) -> int:
        """
        Consumes the specified amount of fuel from this store.

        This is only relevant when `Config.consume_fuel` is configured.

        Raises a `WasmtimeError` if this store's configuration is not configured
        to consume fuel or if the store doesn't have enough fuel remaining.

        Returns the remaining amount of fuel left in the store.
        """
        remaining = c_uint64(0)
        err = ffi.wasmtime_context_consume_fuel(self._context, fuel, byref(remaining))
        if err:
            raise WasmtimeError._from_ptr(err)
        return remaining.value

    def set_wasi(self, wasi: "WasiConfig") -> None:
        """
        TODO
        """
        error = ffi.wasmtime_context_set_wasi(self._context, wasi._ptr)
        delattr(wasi, '_ptr')
        if error:
            raise WasmtimeError._from_ptr(error)

    def __del__(self) -> None:
        if hasattr(self, '_ptr'):
            ffi.wasmtime_store_delete(self._ptr)

Methods

def add_fuel(self, fuel: int) ‑> None

Adds the specified amount of fuel into this store.

This is only relevant when Config.consume_fuel is configured.

This is a required call to ensure that the store has fuel to execute WebAssembly since otherwise stores start with zero fuel.

Raises a WasmtimeError if this store's configuration is not configured to consume fuel.

Expand source code
def add_fuel(self, fuel: int) -> None:
    """
    Adds the specified amount of fuel into this store.

    This is only relevant when `Config.consume_fuel` is configured.

    This is a required call to ensure that the store has fuel to
    execute WebAssembly since otherwise stores start with zero fuel.

    Raises a `WasmtimeError` if this store's configuration is not configured
    to consume fuel.
    """
    err = ffi.wasmtime_context_add_fuel(self._context, fuel)
    if err:
        raise WasmtimeError._from_ptr(err)
def consume_fuel(self, fuel: int) ‑> int

Consumes the specified amount of fuel from this store.

This is only relevant when Config.consume_fuel is configured.

Raises a WasmtimeError if this store's configuration is not configured to consume fuel or if the store doesn't have enough fuel remaining.

Returns the remaining amount of fuel left in the store.

Expand source code
def consume_fuel(self, fuel: int) -> int:
    """
    Consumes the specified amount of fuel from this store.

    This is only relevant when `Config.consume_fuel` is configured.

    Raises a `WasmtimeError` if this store's configuration is not configured
    to consume fuel or if the store doesn't have enough fuel remaining.

    Returns the remaining amount of fuel left in the store.
    """
    remaining = c_uint64(0)
    err = ffi.wasmtime_context_consume_fuel(self._context, fuel, byref(remaining))
    if err:
        raise WasmtimeError._from_ptr(err)
    return remaining.value
def data(self) ‑> Optional[Any]

TODO

Expand source code
def data(self) -> typing.Optional[typing.Any]:
    """
    TODO
    """
    data = ffi.wasmtime_context_get_data(self._context)
    if data:
        return value._unintern(data)
    else:
        return None
def fuel_consumed(self) ‑> int

Returns the amount of fuel consumed by this Store so far.

Raises a WasmtimeError if this store's configuration is not configured to consume fuel.

Expand source code
def fuel_consumed(self) -> int:
    """
    Returns the amount of fuel consumed by this `Store` so far.

    Raises a `WasmtimeError` if this store's configuration is not configured
    to consume fuel.
    """
    fuel = c_uint64(0)
    ok = ffi.wasmtime_context_fuel_consumed(self._context, byref(fuel))
    if ok:
        return fuel.value
    raise WasmtimeError("fuel is not enabled in this store's configuration")
def gc(self) ‑> None

Runs a GC over externref values that have been passed into this Store, cleaning out anything that is no longer referenced.

This is not required to be run manually, but can be done so if you'd like more precise control over when unreferenced externref values are deallocated.

Expand source code
def gc(self) -> None:
    """
    Runs a GC over `externref` values that have been passed into this Store,
    cleaning out anything that is no longer referenced.

    This is not required to be run manually, but can be done so if you'd
    like more precise control over when unreferenced `externref` values are
    deallocated.
    """
    ffi.wasmtime_context_gc(self._context)
def interrupt_handle(self) ‑> wasmtime._store.InterruptHandle

Creates a new interrupt handle through which execution of wasm can be interrupted.

Raises a WasmtimeError if this store's configuration has not been configured to enable interruption.

For more information about this be sure to consult the Rust documentation: https://bytecodealliance.github.io/wasmtime/api/wasmtime/struct.Store.html#method.interrupt_handle

Expand source code
def interrupt_handle(self) -> "InterruptHandle":
    """
    Creates a new interrupt handle through which execution of wasm can be
    interrupted.

    Raises a `WasmtimeError` if this store's configuration has not been
    configured to enable interruption.

    For more information about this be sure to consult the Rust documentation:
    https://bytecodealliance.github.io/wasmtime/api/wasmtime/struct.Store.html#method.interrupt_handle
    """

    return InterruptHandle(self)
def set_wasi(self, wasi: WasiConfig)

TODO

Expand source code
def set_wasi(self, wasi: "WasiConfig") -> None:
    """
    TODO
    """
    error = ffi.wasmtime_context_set_wasi(self._context, wasi._ptr)
    delattr(wasi, '_ptr')
    if error:
        raise WasmtimeError._from_ptr(error)
class Table (store: wasmtime._store.Store, ty: wasmtime._types.TableType, init: Union[wasmtime._value.Val, int, float, ForwardRef(None), ForwardRef('Func'), Any])

Creates a new table within store with the specified ty.

Expand source code
class Table:
    _table: ffi.wasmtime_table_t

    def __init__(self, store: Store, ty: TableType, init: IntoVal):
        """
        Creates a new table within `store` with the specified `ty`.
        """

        init_val = Val._convert(ty.element, init)

        table = ffi.wasmtime_table_t()
        error = ffi.wasmtime_table_new(store._context, ty._ptr, byref(init_val._unwrap_raw()), byref(table))
        if error:
            raise WasmtimeError._from_ptr(error)
        self._table = table

    @classmethod
    def _from_raw(cls, table: ffi.wasmtime_table_t) -> "Table":
        ty: "Table" = cls.__new__(cls)
        ty._table = table
        return ty

    def type(self, store: Storelike) -> TableType:
        """
        Gets the type of this table as a `TableType`
        """

        ptr = ffi.wasmtime_table_type(store._context, byref(self._table))
        return TableType._from_ptr(ptr, None)

    def size(self, store: Storelike) -> int:
        """
        Gets the size, in elements, of this table
        """
        return ffi.wasmtime_table_size(store._context, byref(self._table))

    def grow(self, store: Storelike, amt: int, init: IntoVal) -> int:
        """
        Grows this table by the specified number of slots, using the specified
        initializer for all new table slots.

        Raises a `WasmtimeError` if the table could not be grown.
        Returns the previous size of the table otherwise.
        """
        init_val = Val._convert(self.type(store).element, init)
        prev = c_uint32(0)
        error = ffi.wasmtime_table_grow(store._context, byref(self._table), c_uint32(amt), byref(init_val._unwrap_raw()), byref(prev))
        if error:
            raise WasmtimeError._from_ptr(error)
        return prev.value

    def get(self, store: Store, idx: int) -> Optional[Any]:
        """
        Gets an individual element within this table.

        Returns `None` for null references in the table (i.e. a null `funcref`
        or a null `externref).

        Returns a `Func` for non-null `funcref` table elements.

        Returns the wrapped extern data for non-null `externref` table elements.

        Returns `None` if `idx` is out of bounds.
        """
        raw = ffi.wasmtime_val_t()
        ok = ffi.wasmtime_table_get(store._context, byref(self._table), idx, byref(raw))
        if not ok:
            return None
        val = Val(raw)
        if val.value:
            return val.value
        else:
            return val

    def set(self, store: Store, idx: int, val: IntoVal) -> None:
        """
        Sets an individual element within this table.

        `idx` must be an integer index.

        The `val` specified must be convertible into this table's element
        type. I.e. for a `funcref` table, `val` must either be a `Func` or
        `None`, and for an `externref` table, `val` may be any arbitrary
        external data.

        Raises a `WasmtimeError` if `idx` is out of bounds.
        """
        value = Val._convert(self.type(store).element, val)
        error = ffi.wasmtime_table_set(store._context, byref(self._table), idx, byref(value._unwrap_raw()))
        if error:
            raise WasmtimeError._from_ptr(error)

    def _as_extern(self) -> ffi.wasmtime_extern_t:
        union = ffi.wasmtime_extern_union(table=self._table)
        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_TABLE, union)

Methods

def get(self, store: wasmtime._store.Store, idx: int) ‑> Optional[Any]

Gets an individual element within this table.

Returns None for null references in the table (i.e. a null funcref or a null `externref).

Returns a Func for non-null funcref table elements.

Returns the wrapped extern data for non-null externref table elements.

Returns None if idx is out of bounds.

Expand source code
def get(self, store: Store, idx: int) -> Optional[Any]:
    """
    Gets an individual element within this table.

    Returns `None` for null references in the table (i.e. a null `funcref`
    or a null `externref).

    Returns a `Func` for non-null `funcref` table elements.

    Returns the wrapped extern data for non-null `externref` table elements.

    Returns `None` if `idx` is out of bounds.
    """
    raw = ffi.wasmtime_val_t()
    ok = ffi.wasmtime_table_get(store._context, byref(self._table), idx, byref(raw))
    if not ok:
        return None
    val = Val(raw)
    if val.value:
        return val.value
    else:
        return val
def grow(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], amt: int, init: Union[wasmtime._value.Val, int, float, ForwardRef(None), ForwardRef('Func'), Any]) ‑> int

Grows this table by the specified number of slots, using the specified initializer for all new table slots.

Raises a WasmtimeError if the table could not be grown. Returns the previous size of the table otherwise.

Expand source code
def grow(self, store: Storelike, amt: int, init: IntoVal) -> int:
    """
    Grows this table by the specified number of slots, using the specified
    initializer for all new table slots.

    Raises a `WasmtimeError` if the table could not be grown.
    Returns the previous size of the table otherwise.
    """
    init_val = Val._convert(self.type(store).element, init)
    prev = c_uint32(0)
    error = ffi.wasmtime_table_grow(store._context, byref(self._table), c_uint32(amt), byref(init_val._unwrap_raw()), byref(prev))
    if error:
        raise WasmtimeError._from_ptr(error)
    return prev.value
def set(self, store: wasmtime._store.Store, idx: int, val: Union[wasmtime._value.Val, int, float, ForwardRef(None), ForwardRef('Func'), Any])

Sets an individual element within this table.

idx must be an integer index.

The val specified must be convertible into this table's element type. I.e. for a funcref table, val must either be a Func or None, and for an externref table, val may be any arbitrary external data.

Raises a WasmtimeError if idx is out of bounds.

Expand source code
def set(self, store: Store, idx: int, val: IntoVal) -> None:
    """
    Sets an individual element within this table.

    `idx` must be an integer index.

    The `val` specified must be convertible into this table's element
    type. I.e. for a `funcref` table, `val` must either be a `Func` or
    `None`, and for an `externref` table, `val` may be any arbitrary
    external data.

    Raises a `WasmtimeError` if `idx` is out of bounds.
    """
    value = Val._convert(self.type(store).element, val)
    error = ffi.wasmtime_table_set(store._context, byref(self._table), idx, byref(value._unwrap_raw()))
    if error:
        raise WasmtimeError._from_ptr(error)
def size(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> int

Gets the size, in elements, of this table

Expand source code
def size(self, store: Storelike) -> int:
    """
    Gets the size, in elements, of this table
    """
    return ffi.wasmtime_table_size(store._context, byref(self._table))
def type(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> wasmtime._types.TableType

Gets the type of this table as a TableType

Expand source code
def type(self, store: Storelike) -> TableType:
    """
    Gets the type of this table as a `TableType`
    """

    ptr = ffi.wasmtime_table_type(store._context, byref(self._table))
    return TableType._from_ptr(ptr, None)
class TableType (valtype: wasmtime._types.ValType, limits: wasmtime._types.Limits)
Expand source code
class TableType:
    def __init__(self, valtype: ValType, limits: Limits):
        if not isinstance(limits, Limits):
            raise TypeError("expected Limits")
        type_ptr = take_owned_valtype(valtype)
        ptr = ffi.wasm_tabletype_new(type_ptr, byref(limits.__ffi__()))
        if not ptr:
            raise WasmtimeError("failed to allocate TableType")
        self._ptr = ptr
        self._owner = None

    @classmethod
    def _from_ptr(cls, ptr: 'pointer[ffi.wasm_tabletype_t]', owner: Optional[Any]) -> "TableType":
        ty: "TableType" = cls.__new__(cls)
        if not isinstance(ptr, POINTER(ffi.wasm_tabletype_t)):
            raise TypeError("wrong pointer type")
        ty._ptr = ptr
        ty._owner = owner
        return ty

    @property
    def element(self) -> ValType:
        """
        Returns the type of this table's elements
        """
        ptr = ffi.wasm_tabletype_element(self._ptr)
        return ValType._from_ptr(ptr, self)

    @property
    def limits(self) -> Limits:
        """
        Returns the limits on the size of thi stable
        """
        val = ffi.wasm_tabletype_limits(self._ptr)
        return Limits._from_ffi(val)

    def _as_extern(self) -> "pointer[ffi.wasm_externtype_t]":
        return ffi.wasm_tabletype_as_externtype_const(self._ptr)

    def __del__(self) -> None:
        if hasattr(self, '_owner') and self._owner is None:
            ffi.wasm_tabletype_delete(self._ptr)

Instance variables

var element : wasmtime._types.ValType

Returns the type of this table's elements

Expand source code
@property
def element(self) -> ValType:
    """
    Returns the type of this table's elements
    """
    ptr = ffi.wasm_tabletype_element(self._ptr)
    return ValType._from_ptr(ptr, self)
var limits : wasmtime._types.Limits

Returns the limits on the size of thi stable

Expand source code
@property
def limits(self) -> Limits:
    """
    Returns the limits on the size of thi stable
    """
    val = ffi.wasm_tabletype_limits(self._ptr)
    return Limits._from_ffi(val)
class Trap (message: str)

Common base class for all non-exit exceptions.

Creates a new trap with the given message

Expand source code
class Trap(Exception):
    def __init__(self, message: str):
        """
        Creates a new trap with the given `message`
        """

        vec = message.encode('utf-8')
        self._ptr = ffi.wasmtime_trap_new(ffi.create_string_buffer(vec), len(vec))

    @classmethod
    def _from_ptr(cls, ptr: "pointer[ffi.wasm_trap_t]") -> "Trap":
        if not isinstance(ptr, POINTER(ffi.wasm_trap_t)):
            raise TypeError("wrong pointer type")
        exit_code = c_int(0)
        if ffi.wasmtime_trap_exit_status(ptr, byref(exit_code)):
            exit_trap: ExitTrap = ExitTrap.__new__(ExitTrap)
            exit_trap._ptr = ptr
            exit_trap.code = exit_code.value
            return exit_trap
        else:
            trap: Trap = cls.__new__(cls)
            trap._ptr = ptr
            return trap

    @property
    def message(self) -> str:
        """
        Returns the message for this trap
        """

        message = ffi.wasm_byte_vec_t()
        ffi.wasm_trap_message(self._ptr, byref(message))
        # subtract one to chop off the trailing nul byte
        message.size -= 1
        ret = ffi.to_str(message)
        message.size += 1
        ffi.wasm_byte_vec_delete(byref(message))
        return ret

    @property
    def frames(self) -> List["Frame"]:
        frames = FrameList()
        ffi.wasm_trap_trace(self._ptr, byref(frames.vec))
        ret = []
        for i in range(0, frames.vec.size):
            ret.append(Frame._from_ptr(frames.vec.data[i], frames))
        return ret

    @property
    def trap_code(self) -> Optional[TrapCode]:
        """
        Returns an optional `TrapCode` that corresponds to why this trap
        happened.

        Note that `None` may be returned for manually created traps which do
        not have an associated code with them.
        """
        code = ffi.wasmtime_trap_code_t()
        if ffi.wasmtime_trap_code(self._ptr, byref(code)):
            return TrapCode(code.value)
        return None

    def __str__(self) -> str:
        return self.message

    def __del__(self) -> None:
        if hasattr(self, '_ptr'):
            ffi.wasm_trap_delete(self._ptr)

Ancestors

  • builtins.Exception
  • builtins.BaseException

Subclasses

  • wasmtime._trap.ExitTrap

Instance variables

var frames : List[wasmtime._trap.Frame]
Expand source code
@property
def frames(self) -> List["Frame"]:
    frames = FrameList()
    ffi.wasm_trap_trace(self._ptr, byref(frames.vec))
    ret = []
    for i in range(0, frames.vec.size):
        ret.append(Frame._from_ptr(frames.vec.data[i], frames))
    return ret
var message : str

Returns the message for this trap

Expand source code
@property
def message(self) -> str:
    """
    Returns the message for this trap
    """

    message = ffi.wasm_byte_vec_t()
    ffi.wasm_trap_message(self._ptr, byref(message))
    # subtract one to chop off the trailing nul byte
    message.size -= 1
    ret = ffi.to_str(message)
    message.size += 1
    ffi.wasm_byte_vec_delete(byref(message))
    return ret
var trap_code : Optional[wasmtime._trap.TrapCode]

Returns an optional TrapCode that corresponds to why this trap happened.

Note that None may be returned for manually created traps which do not have an associated code with them.

Expand source code
@property
def trap_code(self) -> Optional[TrapCode]:
    """
    Returns an optional `TrapCode` that corresponds to why this trap
    happened.

    Note that `None` may be returned for manually created traps which do
    not have an associated code with them.
    """
    code = ffi.wasmtime_trap_code_t()
    if ffi.wasmtime_trap_code(self._ptr, byref(code)):
        return TrapCode(code.value)
    return None
class TrapCode (value, names=None, *, module=None, qualname=None, type=None, start=1)

An enumeration.

Expand source code
class TrapCode(Enum):
    # The current stack space was exhausted.
    STACK_OVERFLOW = 0
    # An out-of-bounds memory access.
    MEMORY_OUT_OF_BOUNDS = 1
    # A wasm atomic operation was presented with a not-naturally-aligned linear-memory address.
    HEAP_MISALIGNED = 2
    # An out-of-bounds access to a table.
    TABLE_OUT_OF_BOUNDS = 3
    # Indirect call to a null table entry.
    INDIRECT_CALL_TO_NULL = 4
    # Signature mismatch on indirect call.
    BAD_SIGNATURE = 5
    # An integer arithmetic operation caused an overflow.
    INTEGER_OVERFLOW = 6
    # An integer division by zero.
    INTEGER_DIVISION_BY_ZERO = 7
    # Failed float-to-int conversion.
    BAD_CONVERSION_TO_INTEGER = 8
    # Code that was supposed to have been unreachable was reached.
    UNREACHABLE = 9
    # Execution has potentially run too long and may be interrupted.
    INTERRUPT = 10

Ancestors

  • enum.Enum

Class variables

var BAD_CONVERSION_TO_INTEGER
var BAD_SIGNATURE
var HEAP_MISALIGNED
var INDIRECT_CALL_TO_NULL
var INTEGER_DIVISION_BY_ZERO
var INTEGER_OVERFLOW
var INTERRUPT
var MEMORY_OUT_OF_BOUNDS
var STACK_OVERFLOW
var TABLE_OUT_OF_BOUNDS
var UNREACHABLE
class Val (raw: wasmtime._bindings.wasmtime_val)
Expand source code
class Val:
    # We can't let the extern values we wrap `externref`s around be GC'd, so we
    # pin them in `_id_to_extern`. Additionally, we might make multiple
    # `externref`s to the same extern value, so we count how many references
    # we've created in `_id_to_ref_count`, and only remove a value's entry from
    # `_id_to_extern` once the ref count is zero.
    _id_to_extern: typing.Dict[int, typing.Any] = {}
    _id_to_ref_count: typing.Dict[int, int] = {}

    _raw: typing.Optional[wasmtime_val_t]

    @classmethod
    def i32(cls, val: int) -> "Val":
        """
        Create a new 32-bit integer value
        """
        if not isinstance(val, int):
            raise TypeError("expected an integer")
        ffi = wasmtime_val_t(WASMTIME_I32, wasmtime_valunion(i32=val))
        return Val(ffi)

    @classmethod
    def i64(cls, val: int) -> "Val":
        """
        Create a new 64-bit integer value
        """
        if not isinstance(val, int):
            raise TypeError("expected an integer")
        ffi = wasmtime_val_t(WASMTIME_I64, wasmtime_valunion(i64=val))
        return Val(ffi)

    @classmethod
    def f32(cls, val: float) -> "Val":
        """
        Create a new 32-bit float value
        """
        if not isinstance(val, float):
            raise TypeError("expected a float")
        ffi = wasmtime_val_t(WASMTIME_F32, wasmtime_valunion(f32=val))
        return Val(ffi)

    @classmethod
    def f64(cls, val: float) -> "Val":
        """
        Create a new 64-bit float value
        """
        if not isinstance(val, float):
            raise TypeError("expected a float")
        ffi = wasmtime_val_t(WASMTIME_F64, wasmtime_valunion(f64=val))
        return Val(ffi)

    @classmethod
    def externref(cls, extern: typing.Optional[typing.Any]) -> "Val":
        ffi = wasmtime_val_t(WASMTIME_EXTERNREF)
        ffi.of.externref = POINTER(wasmtime_externref_t)()
        if extern is not None:
            extern_id = _intern(extern)
            ptr = wasmtime_externref_new(extern_id, _externref_finalizer)
            ffi.of.externref = ptr
        return Val(ffi)

    @classmethod
    def funcref(cls, f: "typing.Optional[wasmtime.Func]") -> "Val":
        ffi = wasmtime_val_t(WASMTIME_FUNCREF)
        if f:
            ffi.of.funcref = f._func
        return Val(ffi)

    @classmethod
    def ref_null(cls, ty: ValType) -> "Val":
        """
        Create a null reference value of the given type.

        Raise an exception if `ty` is not a reference type.
        """
        if ty == ValType.externref():
            return Val.externref(None)
        if ty == ValType.funcref():
            return Val.funcref(None)
        raise WasmtimeError("Invalid reference type for `ref_null`: %s" % ty)

    def __init__(self, raw: wasmtime_val_t):
        self._raw = raw

    def __eq__(self, rhs: typing.Any) -> typing.Any:
        if isinstance(rhs, Val):
            return self._unwrap_raw().kind == rhs._unwrap_raw().kind and self.value == rhs.value
        return self.value == rhs

    def __del__(self) -> None:
        if hasattr(self, "_raw") and self._raw is not None:
            wasmtime_val_delete(ctypes.byref(self._raw))

    def _clone(self) -> "Val":
        raw = self._unwrap_raw()
        if raw.kind == WASMTIME_EXTERNREF and raw.of.externref:
            externref = wasmtime_externref_clone(raw.of.externref)
            raw = wasmtime_val_t(WASMTIME_EXTERNREF)
            raw.of.externref = externref
        return Val(raw)

    @classmethod
    def _convert(cls, ty: ValType, val: "IntoVal") -> "Val":
        if isinstance(val, Val):
            if ty != val.type:
                raise TypeError("wrong type of `Val` provided")
            return val
        elif isinstance(val, int):
            if ty == ValType.i32():
                return Val.i32(val)
            if ty == ValType.i64():
                return Val.i64(val)
        elif isinstance(val, float):
            if ty == ValType.f32():
                return Val.f32(val)
            if ty == ValType.f64():
                return Val.f64(val)
        elif isinstance(val, wasmtime.Func):
            return Val.funcref(val)
        elif val is None:
            if ty == ValType.externref():
                return Val.externref(None)
            if ty == ValType.funcref():
                return Val.funcref(None)
        elif ty == ValType.externref():
            return Val.externref(val)
        raise TypeError("don't know how to convert %r to %s" % (val, ty))

    def _into_raw(self) -> wasmtime_val_t:
        raw = self._unwrap_raw()
        self._raw = None
        return raw

    def _unwrap_raw(self) -> wasmtime_val_t:
        if isinstance(self._raw, wasmtime_val_t):
            return self._raw
        else:
            raise WasmtimeError("use of moved `Val`")

    @classmethod
    def _value(cls, raw: wasmtime_val_t) -> typing.Union[int, float, "wasmtime.Func", typing.Any]:
        if raw.kind == WASMTIME_I32.value:
            return raw.of.i32
        if raw.kind == WASMTIME_I64.value:
            return raw.of.i64
        if raw.kind == WASMTIME_F32.value:
            return raw.of.f32
        if raw.kind == WASMTIME_F64.value:
            return raw.of.f64
        if raw.kind == WASMTIME_EXTERNREF.value:
            return Val._as_externref(raw)
        if raw.kind == WASMTIME_FUNCREF.value:
            return Val._as_funcref(raw)
        raise WasmtimeError("Unkown `wasmtime_valkind_t`: {}".format(raw.kind))

    @property
    def value(self) -> typing.Union[int, float, "wasmtime.Func", typing.Any]:
        """
        Get the the underlying value as a python value

        Returns `None` if the value can't be represented in Python, or if the
        value is a null reference type.
        """
        return Val._value(self._unwrap_raw())

    def as_i32(self) -> typing.Optional[int]:
        """
        Get the 32-bit integer value of this value, or `None` if it's not an i32
        """
        raw = self._unwrap_raw()
        if raw.kind == WASMTIME_I32.value:
            return int(raw.of.i32)
        else:
            return None

    def as_i64(self) -> typing.Optional[int]:
        """
        Get the 64-bit integer value of this value, or `None` if it's not an i64
        """
        raw = self._unwrap_raw()
        if raw.kind == WASM_I64.value:
            return raw.of.i64
        else:
            return None

    def as_f32(self) -> typing.Optional[float]:
        """
        Get the 32-bit float value of this value, or `None` if it's not an f32
        """
        raw = self._unwrap_raw()
        if raw.kind == WASMTIME_F32.value:
            return raw.of.f32
        else:
            return None

    def as_f64(self) -> typing.Optional[float]:
        """
        Get the 64-bit float value of this value, or `None` if it's not an f64
        """
        raw = self._unwrap_raw()
        if raw.kind == WASMTIME_F64.value:
            return raw.of.f64
        else:
            return None

    @classmethod
    def _as_externref(cls, raw: wasmtime_val_t) -> typing.Optional[typing.Any]:
        if raw.kind != WASMTIME_EXTERNREF.value:
            return None
        if not raw.of.externref:
            return None
        extern_id = wasmtime_externref_data(raw.of.externref)
        return _unintern(extern_id)

    def as_externref(self) -> typing.Optional[typing.Any]:
        """
        Get the extern data referenced by this `externref` value, or `None` if
        it's not an `externref`.
        """
        return Val._as_externref(self._unwrap_raw())

    @classmethod
    def _as_funcref(cls, raw: wasmtime_val_t) -> typing.Optional["wasmtime.Func"]:
        if raw.kind != WASMTIME_FUNCREF.value:
            return None
        if raw.of.funcref.store_id == 0:
            return None
        else:
            return wasmtime.Func._from_raw(raw.of.funcref)

    def as_funcref(self) -> typing.Optional["wasmtime.Func"]:
        """
        Get the function that this `funcref` value is referencing, or `None` if
        this is not a `funcref` value, or is a null reference.
        """
        return Val._as_funcref(self._unwrap_raw())

    @property
    def type(self) -> ValType:
        """
        Returns the `ValType` corresponding to this `Val`
        """
        kind = self._unwrap_raw().kind
        if kind == WASMTIME_I32.value:
            return ValType.i32()
        elif kind == WASMTIME_I64.value:
            return ValType.i64()
        elif kind == WASMTIME_F32.value:
            return ValType.f32()
        elif kind == WASMTIME_F64.value:
            return ValType.f64()
        elif kind == WASMTIME_V128.value:
            raise Exception("unimplemented v128 type")
        elif kind == WASMTIME_EXTERNREF.value:
            return ValType.externref()
        elif kind == WASMTIME_FUNCREF.value:
            return ValType.funcref()
        else:
            raise Exception("unknown kind %d" % kind.value)

Static methods

def externref(extern: Optional[Any]) ‑> wasmtime._value.Val
Expand source code
@classmethod
def externref(cls, extern: typing.Optional[typing.Any]) -> "Val":
    ffi = wasmtime_val_t(WASMTIME_EXTERNREF)
    ffi.of.externref = POINTER(wasmtime_externref_t)()
    if extern is not None:
        extern_id = _intern(extern)
        ptr = wasmtime_externref_new(extern_id, _externref_finalizer)
        ffi.of.externref = ptr
    return Val(ffi)
def f32(val: float) ‑> wasmtime._value.Val

Create a new 32-bit float value

Expand source code
@classmethod
def f32(cls, val: float) -> "Val":
    """
    Create a new 32-bit float value
    """
    if not isinstance(val, float):
        raise TypeError("expected a float")
    ffi = wasmtime_val_t(WASMTIME_F32, wasmtime_valunion(f32=val))
    return Val(ffi)
def f64(val: float) ‑> wasmtime._value.Val

Create a new 64-bit float value

Expand source code
@classmethod
def f64(cls, val: float) -> "Val":
    """
    Create a new 64-bit float value
    """
    if not isinstance(val, float):
        raise TypeError("expected a float")
    ffi = wasmtime_val_t(WASMTIME_F64, wasmtime_valunion(f64=val))
    return Val(ffi)
def funcref(f: typing.Optional[Func]) ‑> wasmtime._value.Val
Expand source code
@classmethod
def funcref(cls, f: "typing.Optional[wasmtime.Func]") -> "Val":
    ffi = wasmtime_val_t(WASMTIME_FUNCREF)
    if f:
        ffi.of.funcref = f._func
    return Val(ffi)
def i32(val: int) ‑> wasmtime._value.Val

Create a new 32-bit integer value

Expand source code
@classmethod
def i32(cls, val: int) -> "Val":
    """
    Create a new 32-bit integer value
    """
    if not isinstance(val, int):
        raise TypeError("expected an integer")
    ffi = wasmtime_val_t(WASMTIME_I32, wasmtime_valunion(i32=val))
    return Val(ffi)
def i64(val: int) ‑> wasmtime._value.Val

Create a new 64-bit integer value

Expand source code
@classmethod
def i64(cls, val: int) -> "Val":
    """
    Create a new 64-bit integer value
    """
    if not isinstance(val, int):
        raise TypeError("expected an integer")
    ffi = wasmtime_val_t(WASMTIME_I64, wasmtime_valunion(i64=val))
    return Val(ffi)
def ref_null(ty: wasmtime._types.ValType) ‑> wasmtime._value.Val

Create a null reference value of the given type.

Raise an exception if ty is not a reference type.

Expand source code
@classmethod
def ref_null(cls, ty: ValType) -> "Val":
    """
    Create a null reference value of the given type.

    Raise an exception if `ty` is not a reference type.
    """
    if ty == ValType.externref():
        return Val.externref(None)
    if ty == ValType.funcref():
        return Val.funcref(None)
    raise WasmtimeError("Invalid reference type for `ref_null`: %s" % ty)

Instance variables

var type : wasmtime._types.ValType

Returns the ValType corresponding to this Val

Expand source code
@property
def type(self) -> ValType:
    """
    Returns the `ValType` corresponding to this `Val`
    """
    kind = self._unwrap_raw().kind
    if kind == WASMTIME_I32.value:
        return ValType.i32()
    elif kind == WASMTIME_I64.value:
        return ValType.i64()
    elif kind == WASMTIME_F32.value:
        return ValType.f32()
    elif kind == WASMTIME_F64.value:
        return ValType.f64()
    elif kind == WASMTIME_V128.value:
        raise Exception("unimplemented v128 type")
    elif kind == WASMTIME_EXTERNREF.value:
        return ValType.externref()
    elif kind == WASMTIME_FUNCREF.value:
        return ValType.funcref()
    else:
        raise Exception("unknown kind %d" % kind.value)
var value : Union[int, float, wasmtime._func.Func, Any]

Get the the underlying value as a python value

Returns None if the value can't be represented in Python, or if the value is a null reference type.

Expand source code
@property
def value(self) -> typing.Union[int, float, "wasmtime.Func", typing.Any]:
    """
    Get the the underlying value as a python value

    Returns `None` if the value can't be represented in Python, or if the
    value is a null reference type.
    """
    return Val._value(self._unwrap_raw())

Methods

def as_externref(self) ‑> Optional[Any]

Get the extern data referenced by this externref value, or None if it's not an externref.

Expand source code
def as_externref(self) -> typing.Optional[typing.Any]:
    """
    Get the extern data referenced by this `externref` value, or `None` if
    it's not an `externref`.
    """
    return Val._as_externref(self._unwrap_raw())
def as_f32(self) ‑> Optional[float]

Get the 32-bit float value of this value, or None if it's not an f32

Expand source code
def as_f32(self) -> typing.Optional[float]:
    """
    Get the 32-bit float value of this value, or `None` if it's not an f32
    """
    raw = self._unwrap_raw()
    if raw.kind == WASMTIME_F32.value:
        return raw.of.f32
    else:
        return None
def as_f64(self) ‑> Optional[float]

Get the 64-bit float value of this value, or None if it's not an f64

Expand source code
def as_f64(self) -> typing.Optional[float]:
    """
    Get the 64-bit float value of this value, or `None` if it's not an f64
    """
    raw = self._unwrap_raw()
    if raw.kind == WASMTIME_F64.value:
        return raw.of.f64
    else:
        return None
def as_funcref(self) ‑> Optional[wasmtime._func.Func]

Get the function that this funcref value is referencing, or None if this is not a funcref value, or is a null reference.

Expand source code
def as_funcref(self) -> typing.Optional["wasmtime.Func"]:
    """
    Get the function that this `funcref` value is referencing, or `None` if
    this is not a `funcref` value, or is a null reference.
    """
    return Val._as_funcref(self._unwrap_raw())
def as_i32(self) ‑> Optional[int]

Get the 32-bit integer value of this value, or None if it's not an i32

Expand source code
def as_i32(self) -> typing.Optional[int]:
    """
    Get the 32-bit integer value of this value, or `None` if it's not an i32
    """
    raw = self._unwrap_raw()
    if raw.kind == WASMTIME_I32.value:
        return int(raw.of.i32)
    else:
        return None
def as_i64(self) ‑> Optional[int]

Get the 64-bit integer value of this value, or None if it's not an i64

Expand source code
def as_i64(self) -> typing.Optional[int]:
    """
    Get the 64-bit integer value of this value, or `None` if it's not an i64
    """
    raw = self._unwrap_raw()
    if raw.kind == WASM_I64.value:
        return raw.of.i64
    else:
        return None
class ValType
Expand source code
class ValType:
    _ptr: "pointer[ffi.wasm_valtype_t]"
    _owner: Optional[Any]

    @classmethod
    def i32(cls) -> "ValType":
        ptr = ffi.wasm_valtype_new(ffi.WASM_I32)
        return ValType._from_ptr(ptr, None)

    @classmethod
    def i64(cls) -> "ValType":
        ptr = ffi.wasm_valtype_new(ffi.WASM_I64)
        return ValType._from_ptr(ptr, None)

    @classmethod
    def f32(cls) -> "ValType":
        ptr = ffi.wasm_valtype_new(ffi.WASM_F32)
        return ValType._from_ptr(ptr, None)

    @classmethod
    def f64(cls) -> "ValType":
        ptr = ffi.wasm_valtype_new(ffi.WASM_F64)
        return ValType._from_ptr(ptr, None)

    @classmethod
    def externref(cls) -> "ValType":
        ptr = ffi.wasm_valtype_new(ffi.WASM_ANYREF)
        return ValType._from_ptr(ptr, None)

    @classmethod
    def funcref(cls) -> "ValType":
        ptr = ffi.wasm_valtype_new(ffi.WASM_FUNCREF)
        return ValType._from_ptr(ptr, None)

    def __init__(self) -> None:
        raise WasmtimeError("cannot construct directly")

    @classmethod
    def _from_ptr(cls, ptr: "pointer[ffi.wasm_valtype_t]", owner: Optional[Any]) -> "ValType":
        ty: "ValType" = cls.__new__(cls)
        if not isinstance(ptr, POINTER(ffi.wasm_valtype_t)):
            raise TypeError("wrong pointer type")
        ty._ptr = ptr
        ty._owner = owner
        return ty

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, ValType):
            return False
        assert(self._ptr is not None)
        assert(other._ptr is not None)
        kind1 = ffi.wasm_valtype_kind(self._ptr)
        kind2 = ffi.wasm_valtype_kind(other._ptr)
        return kind1 == kind2

    def __ne__(self, other: object) -> bool:
        return not self.__eq__(other)

    def __repr__(self) -> str:
        return str(self)

    def __str__(self) -> str:
        assert(self._ptr is not None)
        kind = ffi.wasm_valtype_kind(self._ptr)
        if kind == ffi.WASM_I32.value:
            return 'i32'
        if kind == ffi.WASM_I64.value:
            return 'i64'
        if kind == ffi.WASM_F32.value:
            return 'f32'
        if kind == ffi.WASM_F64.value:
            return 'f64'
        if kind == ffi.WASM_ANYREF.value:
            return 'anyref'
        if kind == ffi.WASM_FUNCREF.value:
            return 'funcref'
        return 'ValType(%d)' % kind.value

    def __del__(self) -> None:
        if not hasattr(self, '_owner') or not hasattr(self, '_ptr'):
            return
        # If this is owned by another object we don't free it since that object
        # is responsible for freeing the backing memory.
        if self._owner is None:
            ffi.wasm_valtype_delete(self._ptr)

    @classmethod
    def _from_list(cls, items: "pointer[ffi.wasm_valtype_vec_t]", owner: Optional[Any]) -> List["ValType"]:
        types = []
        for i in range(0, items.contents.size):
            types.append(ValType._from_ptr(items.contents.data[i], owner))
        return types

Static methods

def externref() ‑> wasmtime._types.ValType
Expand source code
@classmethod
def externref(cls) -> "ValType":
    ptr = ffi.wasm_valtype_new(ffi.WASM_ANYREF)
    return ValType._from_ptr(ptr, None)
def f32() ‑> wasmtime._types.ValType
Expand source code
@classmethod
def f32(cls) -> "ValType":
    ptr = ffi.wasm_valtype_new(ffi.WASM_F32)
    return ValType._from_ptr(ptr, None)
def f64() ‑> wasmtime._types.ValType
Expand source code
@classmethod
def f64(cls) -> "ValType":
    ptr = ffi.wasm_valtype_new(ffi.WASM_F64)
    return ValType._from_ptr(ptr, None)
def funcref() ‑> wasmtime._types.ValType
Expand source code
@classmethod
def funcref(cls) -> "ValType":
    ptr = ffi.wasm_valtype_new(ffi.WASM_FUNCREF)
    return ValType._from_ptr(ptr, None)
def i32() ‑> wasmtime._types.ValType
Expand source code
@classmethod
def i32(cls) -> "ValType":
    ptr = ffi.wasm_valtype_new(ffi.WASM_I32)
    return ValType._from_ptr(ptr, None)
def i64() ‑> wasmtime._types.ValType
Expand source code
@classmethod
def i64(cls) -> "ValType":
    ptr = ffi.wasm_valtype_new(ffi.WASM_I64)
    return ValType._from_ptr(ptr, None)
class WasiConfig
Expand source code
class WasiConfig:
    def __init__(self) -> None:
        self._ptr = ffi.wasi_config_new()

    @setter_property
    def argv(self, argv: List[str]) -> None:
        """
        Explicitly configure the `argv` for this WASI configuration
        """
        ptrs = to_char_array(argv)
        ffi.wasi_config_set_argv(self._ptr, c_int(len(argv)), ptrs)

    def inherit_argv(self) -> None:
        ffi.wasi_config_inherit_argv(self._ptr)

    @setter_property
    def env(self, pairs: Iterable[Iterable]) -> None:
        """
        Configure environment variables to be returned for this WASI
        configuration.

        The `pairs` provided must be an iterable list of key/value pairs of
        environment variables.
        """
        names = []
        values = []
        for name, value in pairs:
            names.append(name)
            values.append(value)
        name_ptrs = to_char_array(names)
        value_ptrs = to_char_array(values)
        ffi.wasi_config_set_env(self._ptr, c_int(
            len(names)), name_ptrs, value_ptrs)

    def inherit_env(self) -> None:
        """
        Configures the environment variables available within WASI to be those
        in this own process's environment. All environment variables are
        inherited.
        """
        ffi.wasi_config_inherit_env(self._ptr)

    @setter_property
    def stdin_file(self, path: str) -> None:
        """
        Configures a file to be used as the stdin stream of this WASI
        configuration.

        Reads of the stdin stream will read the path specified.

        The file must already exist on the filesystem. If it cannot be
        opened then `WasmtimeError` is raised.
        """
        res = ffi.wasi_config_set_stdin_file(
            self._ptr, c_char_p(path.encode('utf-8')))
        if not res:
            raise WasmtimeError("failed to set stdin file")

    def inherit_stdin(self) -> None:
        """
        Configures this own process's stdin to be used as the WASI program's
        stdin.

        Reads of the stdin stream will read this process's stdin.
        """
        ffi.wasi_config_inherit_stdin(self._ptr)

    @setter_property
    def stdout_file(self, path: str) -> None:
        """
        Configures a file to be used as the stdout stream of this WASI
        configuration.

        Writes to stdout will be written to the file specified.

        The file specified will be created if it doesn't exist, or truncated if
        it already exists. It must be available to open for writing. If it
        cannot be opened for writing then `WasmtimeError` is raised.
        """
        res = ffi.wasi_config_set_stdout_file(
            self._ptr, c_char_p(path.encode('utf-8')))
        if not res:
            raise WasmtimeError("failed to set stdout file")

    def inherit_stdout(self) -> None:
        """
        Configures this own process's stdout to be used as the WASI program's
        stdout.

        Writes to stdout stream will write to this process's stdout.
        """
        ffi.wasi_config_inherit_stdout(self._ptr)

    @setter_property
    def stderr_file(self, path: str) -> None:
        """
        Configures a file to be used as the stderr stream of this WASI
        configuration.

        Writes to stderr will be written to the file specified.

        The file specified will be created if it doesn't exist, or truncated if
        it already exists. It must be available to open for writing. If it
        cannot be opened for writing then `WasmtimeError` is raised.
        """
        res = ffi.wasi_config_set_stderr_file(
            self._ptr, c_char_p(path.encode('utf-8')))
        if not res:
            raise WasmtimeError("failed to set stderr file")

    def inherit_stderr(self) -> None:
        """
        Configures this own process's stderr to be used as the WASI program's
        stderr.

        Writes to stderr stream will write to this process's stderr.
        """
        ffi.wasi_config_inherit_stderr(self._ptr)

    def preopen_dir(self, path: str, guest_path: str) -> None:
        path_ptr = c_char_p(path.encode('utf-8'))
        guest_path_ptr = c_char_p(guest_path.encode('utf-8'))
        ffi.wasi_config_preopen_dir(self._ptr, path_ptr, guest_path_ptr)

    def __del__(self) -> None:
        if hasattr(self, '_ptr'):
            ffi.wasi_config_delete(self._ptr)

Instance variables

var argv

Explicitly configure the argv for this WASI configuration

Note that this field can only be set, it cannot be read

var env

Configure environment variables to be returned for this WASI configuration.

The pairs provided must be an iterable list of key/value pairs of environment variables.

Note that this field can only be set, it cannot be read

var stderr_file

Configures a file to be used as the stderr stream of this WASI configuration.

Writes to stderr will be written to the file specified.

The file specified will be created if it doesn't exist, or truncated if it already exists. It must be available to open for writing. If it cannot be opened for writing then WasmtimeError is raised.

Note that this field can only be set, it cannot be read

var stdin_file

Configures a file to be used as the stdin stream of this WASI configuration.

Reads of the stdin stream will read the path specified.

The file must already exist on the filesystem. If it cannot be opened then WasmtimeError is raised.

Note that this field can only be set, it cannot be read

var stdout_file

Configures a file to be used as the stdout stream of this WASI configuration.

Writes to stdout will be written to the file specified.

The file specified will be created if it doesn't exist, or truncated if it already exists. It must be available to open for writing. If it cannot be opened for writing then WasmtimeError is raised.

Note that this field can only be set, it cannot be read

Methods

def inherit_argv(self) ‑> None
Expand source code
def inherit_argv(self) -> None:
    ffi.wasi_config_inherit_argv(self._ptr)
def inherit_env(self) ‑> None

Configures the environment variables available within WASI to be those in this own process's environment. All environment variables are inherited.

Expand source code
def inherit_env(self) -> None:
    """
    Configures the environment variables available within WASI to be those
    in this own process's environment. All environment variables are
    inherited.
    """
    ffi.wasi_config_inherit_env(self._ptr)
def inherit_stderr(self) ‑> None

Configures this own process's stderr to be used as the WASI program's stderr.

Writes to stderr stream will write to this process's stderr.

Expand source code
def inherit_stderr(self) -> None:
    """
    Configures this own process's stderr to be used as the WASI program's
    stderr.

    Writes to stderr stream will write to this process's stderr.
    """
    ffi.wasi_config_inherit_stderr(self._ptr)
def inherit_stdin(self) ‑> None

Configures this own process's stdin to be used as the WASI program's stdin.

Reads of the stdin stream will read this process's stdin.

Expand source code
def inherit_stdin(self) -> None:
    """
    Configures this own process's stdin to be used as the WASI program's
    stdin.

    Reads of the stdin stream will read this process's stdin.
    """
    ffi.wasi_config_inherit_stdin(self._ptr)
def inherit_stdout(self) ‑> None

Configures this own process's stdout to be used as the WASI program's stdout.

Writes to stdout stream will write to this process's stdout.

Expand source code
def inherit_stdout(self) -> None:
    """
    Configures this own process's stdout to be used as the WASI program's
    stdout.

    Writes to stdout stream will write to this process's stdout.
    """
    ffi.wasi_config_inherit_stdout(self._ptr)
def preopen_dir(self, path: str, guest_path: str) ‑> None
Expand source code
def preopen_dir(self, path: str, guest_path: str) -> None:
    path_ptr = c_char_p(path.encode('utf-8'))
    guest_path_ptr = c_char_p(guest_path.encode('utf-8'))
    ffi.wasi_config_preopen_dir(self._ptr, path_ptr, guest_path_ptr)
class WasmtimeError (message: str)

Common base class for all non-exit exceptions.

Expand source code
class WasmtimeError(Exception):
    def __init__(self, message: str):
        self.message = message

    @classmethod
    def _from_ptr(cls, ptr: pointer) -> 'WasmtimeError':
        from . import _ffi as ffi
        if not isinstance(ptr, POINTER(ffi.wasmtime_error_t)):
            raise TypeError("wrong pointer type")
        message_vec = ffi.wasm_byte_vec_t()
        ffi.wasmtime_error_message(ptr, byref(message_vec))
        message = ffi.to_str(message_vec)
        ffi.wasm_byte_vec_delete(byref(message_vec))
        ffi.wasmtime_error_delete(ptr)
        return WasmtimeError(message)

    def __str__(self) -> str:
        return self.message

Ancestors

  • builtins.Exception
  • builtins.BaseException