1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* \file wasmtime/global.hh
*/
#ifndef WASMTIME_GLOBAL_HH
#define WASMTIME_GLOBAL_HH
#include <wasmtime/error.hh>
#include <wasmtime/global.h>
#include <wasmtime/store.hh>
#include <wasmtime/types/global.hh>
#include <wasmtime/val.hh>
namespace wasmtime {
/**
* \brief A WebAssembly global.
*
* This class represents a WebAssembly global, either created through
* instantiating a module or a host global. Globals contain a WebAssembly value
* and can be read and optionally written to.
*
* 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 as the first
* argument to the functions defined on `Global`. Note that if the wrong `Store`
* is passed in then the process will be aborted.
*/
class Global {
friend class Instance;
wasmtime_global_t global;
public:
/// Creates as global from the raw underlying C API representation.
Global(wasmtime_global_t global) : global(global) {}
/**
* \brief Create a new WebAssembly global.
*
* \param cx the store in which to create the global
* \param ty the type that this global will have
* \param init the initial value of the global
*
* This function can fail if `init` does not have a value that matches `ty`.
*/
static Result<Global> create(Store::Context cx, const GlobalType &ty,
const Val &init) {
wasmtime_global_t global;
auto *error = wasmtime_global_new(cx.ptr, ty.ptr.get(), &init.val, &global);
if (error != nullptr) {
return Error(error);
}
return Global(global);
}
/// Returns the type of this global.
GlobalType type(Store::Context cx) const {
return wasmtime_global_type(cx.ptr, &global);
}
/// Returns the current value of this global.
Val get(Store::Context cx) const {
Val val;
wasmtime_global_get(cx.ptr, &global, &val.val);
return val;
}
/// Sets this global to a new value.
///
/// This can fail if `val` has the wrong type or if this global isn't mutable.
Result<std::monostate> set(Store::Context cx, const Val &val) const {
auto *error = wasmtime_global_set(cx.ptr, &global, &val.val);
if (error != nullptr) {
return Error(error);
}
return std::monostate();
}
/// Returns the raw underlying C API global this is using.
const wasmtime_global_t &capi() const { return global; }
};
} // namespace wasmtime
#endif // WASMTIME_GLOBAL_HH