* \brief A WebAssembly instance. * * This class represents a WebAssembly instance, created by instantiating a * module. An instance is the collection of items exported by the module, which * can be accessed through the `Store` that owns the instance. * * Note that this type does not itself own any resources. It points to resources * owned within a `Store` and the `Store` must be passed in a
| 30 | * `Store` is passed in then the process will be aborted. |
| 31 | */ |
| 32 | class Instance { |
| 33 | friend class Linker; |
| 34 | friend class Caller; |
| 35 | |
| 36 | wasmtime_instance_t instance; |
| 37 | |
| 38 | public: |
| 39 | /// Creates a new instance from the raw underlying C API representation. |
| 40 | Instance(wasmtime_instance_t instance) : instance(instance) {} |
| 41 | |
| 42 | /** |
| 43 | * \brief Instantiates the module `m` with the provided `imports` |
| 44 | * |
| 45 | * \param cx the store in which to instantiate the provided module |
| 46 | * \param m the module to instantiate |
| 47 | * \param imports the list of imports to use to instantiate the module |
| 48 | * |
| 49 | * This `imports` parameter is expected to line up 1:1 with the imports |
| 50 | * required by the `m`. The type of `m` can be inspected to determine in which |
| 51 | * order to provide the imports. Note that this is a relatively low-level API |
| 52 | * and it's generally recommended to use `Linker` instead for name-based |
| 53 | * instantiation. |
| 54 | * |
| 55 | * This function can return an error if any of the `imports` have the wrong |
| 56 | * type, or if the wrong number of `imports` is provided. |
| 57 | */ |
| 58 | static TrapResult<Instance> create(Store::Context cx, const Module &m, |
| 59 | const std::vector<Extern> &imports) { |
| 60 | std::vector<wasmtime_extern_t> raw_imports; |
| 61 | for (const auto &item : imports) { |
| 62 | raw_imports.push_back(wasmtime_extern_t{}); |
| 63 | auto &last = raw_imports.back(); |
| 64 | detail::cvt_extern(item, last); |
| 65 | } |
| 66 | wasmtime_instance_t instance; |
| 67 | wasm_trap_t *trap = nullptr; |
| 68 | auto *error = wasmtime_instance_new(cx.ptr, m.capi(), raw_imports.data(), |
| 69 | raw_imports.size(), &instance, &trap); |
| 70 | if (error != nullptr) { |
| 71 | return TrapError(Error(error)); |
| 72 | } |
| 73 | if (trap != nullptr) { |
| 74 | return TrapError(Trap(trap)); |
| 75 | } |
| 76 | return Instance(instance); |
| 77 | } |
| 78 | |
| 79 | /** |
| 80 | * \brief Load an instance's export by name. |
| 81 | * |
| 82 | * This function will look for an export named `name` on this instance and, if |
| 83 | * found, return it as an `Extern`. |
| 84 | */ |
| 85 | std::optional<Extern> get(Store::Context cx, std::string_view name) { |
| 86 | wasmtime_extern_t e; |
| 87 | if (!wasmtime_instance_export_get(cx.ptr, &instance, name.data(), |
| 88 | name.size(), &e)) { |
| 89 | return std::nullopt; |
no outgoing calls
no test coverage detected