Coverage for wasmtime/component/_instance.py: 100%
32 statements
« prev ^ index » next coverage.py v7.11.3, created at 2025-12-01 19:40 +0000
« prev ^ index » next coverage.py v7.11.3, created at 2025-12-01 19:40 +0000
1import ctypes
3from .. import _ffi as ffi, WasmtimeError, Storelike
4from ctypes import byref
5from typing import Optional, Union
6from ._component import ExportIndex
7from ._func import Func
10class Instance:
11 _instance: ffi.wasmtime_component_instance_t
13 def __init__(self) -> None:
14 raise WasmtimeError("Cannot directly construct an `Instance`")
16 @classmethod
17 def _from_raw(cls, instance: ffi.wasmtime_component_instance_t) -> "Instance":
18 ty: "Instance" = cls.__new__(cls)
19 ty._instance = instance
20 return ty
22 def get_export_index(self, store: Storelike, name: str, instance: Optional[ExportIndex] = None) -> Optional[ExportIndex]:
23 """
24 Retrieves the export index for the export named `name` from this
25 component instance.
27 If `instance` is provided then the export is looked up within that
28 nested instance.
30 Returns `None` if no such export exists otherwise returns the export
31 index.
32 """
33 name_bytes = name.encode('utf-8')
34 name_buf = ctypes.create_string_buffer(name_bytes)
36 ptr = ffi.wasmtime_component_instance_get_export_index(
37 byref(self._instance),
38 store._context(),
39 instance.ptr() if instance is not None else None,
40 name_buf,
41 len(name_bytes))
42 if ptr:
43 return ExportIndex._from_ptr(ptr)
44 return None
46 def get_func(self, store: Storelike, index: Union[ExportIndex, str]) -> Optional[Func]:
47 """
48 Retrieves the function export for the given export index.
50 Returns `None` if the export index does not correspond to a function
51 export and otherwise returns the function.
52 """
53 if isinstance(index, str):
54 ei = self.get_export_index(store, index)
55 if ei is None:
56 return None
57 index = ei
59 raw = ffi.wasmtime_component_func_t()
60 found = ffi.wasmtime_component_instance_get_func(
61 byref(self._instance),
62 store._context(),
63 index.ptr(),
64 byref(raw))
65 if found:
66 return Func._from_raw(raw)
67 return None