* \brief Representation of a WebAssembly `externref` value. * * This class represents an value that cannot be forged by WebAssembly itself. * All `ExternRef` values are guaranteed to be created by the host and its * embedding. It's suitable to place private data structures in here which * WebAssembly will not have access to, only other host functions will have * access to them. * * Note th
| 25 | * never be candidates for garbage collection. |
| 26 | */ |
| 27 | class ExternRef { |
| 28 | WASMTIME_TOP_REF_WRAPPER(ExternRef, wasmtime_externref); |
| 29 | |
| 30 | private: |
| 31 | static void finalizer(void *ptr) { |
| 32 | std::unique_ptr<std::any> _ptr(static_cast<std::any *>(ptr)); |
| 33 | } |
| 34 | |
| 35 | public: |
| 36 | /// Creates a new `externref` value from the provided argument. |
| 37 | /// |
| 38 | /// Note that `val` should be safe to send across threads and should own any |
| 39 | /// memory that it points to. Also note that `ExternRef` is similar to a |
| 40 | /// `std::shared_ptr` in that there can be many references to the same value. |
| 41 | explicit ExternRef(Store::Context cx, std::any val) { |
| 42 | void *ptr = std::make_unique<std::any>(val).release(); |
| 43 | bool ok = wasmtime_externref_new(cx.capi(), ptr, finalizer, &this->raw); |
| 44 | if (!ok) { |
| 45 | fprintf(stderr, "failed to allocate a new externref"); |
| 46 | abort(); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /// Returns the underlying host data associated with this `ExternRef`. |
| 51 | std::any &data(Store::Context cx) { |
| 52 | return *static_cast<std::any *>(wasmtime_externref_data(cx.capi(), &raw)); |
| 53 | } |
| 54 | }; |
| 55 | |
| 56 | } // namespace wasmtime |
| 57 |