#include "ServiceInterface.hpp" #include #include #include #include #include #include #include // Service plugin, schema v1. The plugin object is the service: it derives // IPlugin (for the loader) and ICalc (the host interface, which derives // IService). State (the running total) survives reloads via the v2 state // ABI, serialized with the reflection JSON serializer. namespace { struct StateV1 { int total = 0; }; class CalcPlugin final : public Void::Plugin::IPlugin, public VoidTest::ICalc { public: // IPlugin [[nodiscard]] std::string_view name() const noexcept override { return "CalcPlugin"; } // IService [[nodiscard]] std::string_view service_name() const override { return "CalcPlugin"; } // ICalc int accumulate(int delta) override { return m_total.fetch_add(delta, std::memory_order_relaxed) + delta; } [[nodiscard]] int version() const override { return 1; } std::atomic m_total{0}; }; } // namespace template <> struct Void::Json::StateTraits { static constexpr std::uint32_t version = 1; }; extern "C" { void* void_plugin_create() { return new CalcPlugin; } void void_plugin_destroy(void* p) { delete static_cast(p); } Void::Plugin::PluginInfo void_plugin_info() { return { .abi_version = Void::Plugin::ABI_VERSION, .name = "CalcPlugin", .plugin_version = "1.0.0", .description = "Calc service plugin (schema v1)", }; } // Hand the host the IService subobject of the plugin's ICalc. Void::Service::IService* void_plugin_service(void* instance) { auto* self = static_cast(instance); return static_cast( static_cast(self)); } std::uint32_t void_plugin_state_version() { return 1; } const char* void_plugin_serialize_state(void* instance) { const auto* self = static_cast(instance); const StateV1 state{.total = self->m_total.load(std::memory_order_relaxed)}; const auto json = Void::Json::serialize(Void::Json::to_versioned_json(state)); char* out = static_cast(std::malloc(json.size() + 1)); if (out != nullptr) { std::memcpy(out, json.c_str(), json.size() + 1); } return out; } void void_plugin_free_string(const char* s) { std::free(const_cast(s)); // NOLINT } int void_plugin_deserialize_state(void* instance, const char* json, std::uint32_t /*from_version*/) { auto* self = static_cast(instance); const auto parsed = Void::Json::parse(json); if (!parsed.has_value()) { return 1; } const auto state = Void::Json::from_versioned_json(*parsed); if (!state.has_value()) { return 2; } self->m_total.store(state->total, std::memory_order_relaxed); return 0; } } // extern "C"