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

1import ctypes 

2 

3from .. import _ffi as ffi, WasmtimeError, Storelike 

4from ctypes import byref 

5from typing import Optional, Union 

6from ._component import ExportIndex 

7from ._func import Func 

8 

9 

10class Instance: 

11 _instance: ffi.wasmtime_component_instance_t 

12 

13 def __init__(self) -> None: 

14 raise WasmtimeError("Cannot directly construct an `Instance`") 

15 

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 

21 

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. 

26 

27 If `instance` is provided then the export is looked up within that 

28 nested instance. 

29 

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) 

35 

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 

45 

46 def get_func(self, store: Storelike, index: Union[ExportIndex, str]) -> Optional[Func]: 

47 """ 

48 Retrieves the function export for the given export index. 

49 

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 

58 

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