Coverage for wasmtime/_globals.py: 95%

41 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-02-20 16:25 +0000

1from . import _ffi as ffi 

2from ctypes import * 

3from wasmtime import GlobalType, Val, WasmtimeError 

4from typing import Any 

5from ._store import Storelike 

6 

7 

8class Global: 

9 _global: ffi.wasmtime_global_t 

10 

11 def __init__(self, store: Storelike, ty: GlobalType, val: Any): 

12 if not isinstance(ty, GlobalType): 

13 raise TypeError("expected a GlobalType") 

14 val = Val._convert_to_raw(store, ty.content, val) 

15 global_ = ffi.wasmtime_global_t() 

16 error = ffi.wasmtime_global_new( 

17 store._context(), 

18 ty.ptr(), 

19 byref(val), 

20 byref(global_)) 

21 ffi.wasmtime_val_unroot(store._context(), byref(val)) 

22 if error: 

23 raise WasmtimeError._from_ptr(error) 

24 self._global = global_ 

25 

26 @classmethod 

27 def _from_raw(cls, global_: ffi.wasmtime_global_t) -> "Global": 

28 ty: "Global" = cls.__new__(cls) 

29 ty._global = global_ 

30 return ty 

31 

32 def type(self, store: Storelike) -> GlobalType: 

33 """ 

34 Gets the type of this global as a `GlobalType` 

35 """ 

36 

37 ptr = ffi.wasmtime_global_type(store._context(), byref(self._global)) 

38 return GlobalType._from_ptr(ptr, None) 

39 

40 def value(self, store: Storelike) -> Any: 

41 """ 

42 Gets the current value of this global 

43 

44 Returns a native python type 

45 """ 

46 raw = ffi.wasmtime_val_t() 

47 ffi.wasmtime_global_get(store._context(), byref(self._global), byref(raw)) 

48 val = Val._from_raw(store, raw) 

49 if val.value is not None: 

50 return val.value 

51 else: 

52 return val 

53 

54 def set_value(self, store: Storelike, val: Any) -> None: 

55 """ 

56 Sets the value of this global to a new value 

57 """ 

58 val = Val._convert_to_raw(store, self.type(store).content, val) 

59 error = ffi.wasmtime_global_set(store._context(), byref(self._global), byref(val)) 

60 ffi.wasmtime_val_unroot(store._context(), byref(val)) 

61 if error: 

62 raise WasmtimeError._from_ptr(error) 

63 

64 def _as_extern(self) -> ffi.wasmtime_extern_t: 

65 union = ffi.wasmtime_extern_union(global_=self._global) 

66 return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_GLOBAL, union)