Coverage for wasmtime/_instance_pre.py: 86%

29 statements  

« prev     ^ index     » next       coverage.py v7.11.3, created at 2026-05-07 14:30 +0000

1import ctypes 

2from . import _ffi as ffi 

3from ._managed import Managed 

4from wasmtime import WasmtimeError 

5from ._store import Storelike 

6from ._module import Module 

7from ._instance import Instance 

8from ._func import enter_wasm 

9 

10 

11class InstancePre(Managed["ctypes._Pointer[ffi.wasmtime_instance_pre_t]"]): 

12 """ 

13 A pre-instantiated module with all imports already satisfied. 

14 

15 `InstancePre` allows you to skip the import-resolution step on every call 

16 to `instantiate`, which can improve performance when creating many 

17 instances of the same module. 

18 

19 Created via `Linker.instantiate_pre`. 

20 """ 

21 

22 def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_instance_pre_t]") -> None: 

23 ffi.wasmtime_instance_pre_delete(ptr) 

24 

25 def instantiate(self, store: Storelike) -> Instance: 

26 """ 

27 Instantiates the pre-linked module in the given store. 

28 

29 Raises a `WasmtimeError` on error or a `wasmtime.Trap` if a trap occurs 

30 during instantiation. 

31 """ 

32 instance = ffi.wasmtime_instance_t() 

33 with enter_wasm(store) as trap: 

34 error = ffi.wasmtime_instance_pre_instantiate( 

35 self.ptr(), store._context(), ctypes.byref(instance), trap) 

36 if error: 

37 raise WasmtimeError._from_ptr(error) 

38 return Instance._from_raw(instance) 

39 

40 @property 

41 def module(self) -> Module: 

42 """ 

43 Returns the `Module` that this `InstancePre` was 

44 created from. 

45 """ 

46 ptr = ffi.wasmtime_instance_pre_module(self.ptr()) 

47 return Module._from_ptr(ptr) 

48 

49 @classmethod 

50 def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_instance_pre_t]") -> 'InstancePre': 

51 if not isinstance(ptr, ctypes.POINTER(ffi.wasmtime_instance_pre_t)): 

52 raise TypeError("wrong pointer type") 

53 pre: InstancePre = cls.__new__(cls) 

54 pre._set_ptr(ptr) 

55 return pre