glibdbus

String representation of GVariant


Is there a function to parse a generic glib GVariant pointer into a const char*?

Such as the way it's done in DBus?

signal time=1717768489.237441 sender=:1.22 -> destination=(null destination) serial=17 path=/org/bluez/hci0; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged

string "org.bluez.Adapter1"
   array [
      dict entry(
         string "Powered"
         variant             boolean false
      )
      dict entry(
         string "Discovering"
         variant             boolean false
      )
   ]
   array [
   ]

Solution

  • I finally found it! Obviously, I'd much rather prefer an std::string than const char*, but since this library is very C-stylish I had no such hope. The somewhat cumbersome API can be hidden in a helper function:

    std::string print_variant(GVariant* v) {
      auto* res = g_variant_print_string(v, nullptr, true);
      if (nullptr == res->str) {
        return "NULL";
      }
      std::string retval(res->str, res->len);
      g_string_free(res, true);
      return retval;
    }