|
| 1 | +#ifndef GODOT_WASM_EXTENSION_H |
| 2 | +#define GODOT_WASM_EXTENSION_H |
| 3 | + |
| 4 | +#include <map> |
| 5 | +#include <string> |
| 6 | +#include <vector> |
| 7 | +#include <wasm.h> |
| 8 | +#include "../defs.h" |
| 9 | +#include "../defer.h" |
| 10 | +#include "../store.h" |
| 11 | + |
| 12 | +namespace godot { |
| 13 | + class Wasm; // Forward declare to avoid circular dependency |
| 14 | + |
| 15 | + namespace godot_wasm { |
| 16 | + typedef wasm_trap_t* (*extension_callback_t)(Wasm*, const wasm_val_vec_t*, wasm_val_vec_t*); |
| 17 | + typedef std::tuple<std::vector<wasm_valkind_enum>, std::vector<wasm_valkind_enum>, extension_callback_t> callback_signature; |
| 18 | + |
| 19 | + class Extension { |
| 20 | + private: |
| 21 | + Wasm* wasm; // Non-owning pointer to the Wasm instance |
| 22 | + std::map<std::string, callback_signature> signatures; |
| 23 | + |
| 24 | + wasm_func_t* create_callback(const callback_signature& signature) { |
| 25 | + const auto& param_types = std::get<0>(signature); |
| 26 | + const auto& result_types = std::get<1>(signature); |
| 27 | + |
| 28 | + wasm_valtype_vec_t params; |
| 29 | + wasm_valtype_vec_new_uninitialized(¶ms, param_types.size()); |
| 30 | + for (size_t i = 0; i < param_types.size(); i++) params.data[i] = wasm_valtype_new(param_types[i]); |
| 31 | + DEFER(wasm_valtype_vec_delete(¶ms)); |
| 32 | + |
| 33 | + wasm_valtype_vec_t results; |
| 34 | + wasm_valtype_vec_new_uninitialized(&results, result_types.size()); |
| 35 | + for (size_t i = 0; i < result_types.size(); i++) results.data[i] = wasm_valtype_new(result_types[i]); |
| 36 | + DEFER(wasm_valtype_vec_delete(&results)); |
| 37 | + |
| 38 | + wasm_functype_t* functype = wasm_functype_new(¶ms, &results); |
| 39 | + DEFER(wasm_functype_delete(functype)); |
| 40 | + |
| 41 | + extension_callback_t callback = std::get<2>(signature); |
| 42 | + |
| 43 | + return wasm_func_new_with_env(STORE, functype, (wasm_func_callback_with_env_t)callback, wasm, NULL); |
| 44 | + } |
| 45 | + |
| 46 | + protected: |
| 47 | + void register_callback( |
| 48 | + const String& import_name, |
| 49 | + const std::vector<wasm_valkind_enum>& param_types, |
| 50 | + const std::vector<wasm_valkind_enum>& result_types, |
| 51 | + extension_callback_t callback |
| 52 | + ) { |
| 53 | + std::string key = std::string(import_name.utf8().get_data()); |
| 54 | + signatures[key] = std::make_tuple(param_types, result_types, callback); |
| 55 | + } |
| 56 | + |
| 57 | + public: |
| 58 | + Extension(Wasm* wasm_instance): wasm(wasm_instance) {} |
| 59 | + virtual ~Extension() {} |
| 60 | + |
| 61 | + virtual wasm_func_t* get_callback(const String &name) final { |
| 62 | + std::string key = std::string(name.utf8().get_data()); |
| 63 | + if (signatures.count(key)) { |
| 64 | + return create_callback(signatures[key]); |
| 65 | + } |
| 66 | + return NULL; |
| 67 | + } |
| 68 | + }; |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +#endif |
0 commit comments