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