Search code examples
cglibdbusgvariant

GLib - getting the number of strings in array returned over D-Bus


I am getting an array of strings via a function call over D-Bus as follows. I am using GLib then to parse the returned values. The code below is greatly simplified. I can read each string returned using g_variant_iter_loop and the iterator.

How can I first determine how many strings have been returned in the array?

I need to allocate memory dynamically first depending on how many strings have been returned, before reading the actual strings. This may seem simple, but i've been looking online for the best way to do this without success. Thanks in advance.

GVariant * val_returned = g_dbus_connection_call_sync(connection,
                          SERVICE,
                          OBJECT,
                          IFACE,
                          "GetStringsArray",
                          NULL,
                          G_VARIANT_TYPE("(as)"),
                          G_DBUS_CALL_FLAGS_NONE,
                         -1,
                          NULL,
                          &err);

g_autoptr(GVariantIter) iterator = NULL;
g_variant_get(val_returned, "(as)", &iterator);

// Need to determine how many strings have been read into the array
// Use g_variant_iter_loop to retrieve each string as a gchar*

Solution

  • Call g_variant_iter_n_children (iterator).