对复杂格式进行gvariant解析

时间:2015-04-02 15:36:13

标签: linux gtk glib dbus

在我的应用程序中,我将通过dbus获取消息,必须使用gvariant函数进行解析。

格式字符串为G_VARIANT_TYPE(“a(ysb((sss)(sss)))”

构建gVariant的示例代码如下所示

int ParseVariant(GVariant * value);

int main()
{

GVariantBuilder *builder;
GVariant *value;


builder = g_variant_builder_new (G_VARIANT_TYPE ("a(ysb((sss)(sss)))"));
g_variant_builder_add (builder, "(ysb((sss)(sss)))", 'J', "Test1", TRUE, "Hn", "di", "hedfs", "dd", "dr", "hdf");
g_variant_builder_add (builder, "(ysb((sss)(sss)))", 'J', "Test2", TRUE, "Hn", "di", "hedfs", "dd", "dr", "hdf");
//g_variant_builder_add (builder, "(ysb((sss)(sss)))", 'J', "Test3", TRUE, "Hn", "di", "hedfs", "dd", "dr", "hdf");


GVariant *result = g_variant_new ("((yu)ya(ysb((sss)(sss))))", 'R', 23, 'E', builder);

g_variant_builder_unref (builder);
ParseVariant (result);
}

我正在寻找一个解析器函数(ParseVariant(result)),使用它我可以提取变体结果的每个元素。

对此的任何帮助都非常感谢。

提前致谢。

1 个答案:

答案 0 :(得分:4)

以下是我在Gtk邮件列表中提供的答案,其中您还提供了ParseVariant()

#include <glib.h>
#include <glib/gstdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>

int ParseVariant (GVariant *value)
{
    GVariant * list;
    gchar ch1,ch2,ch3;
    gchar *str1,*str2,*str3,*str4,*str5,*str6,*str7;
    gboolean bool1;
    gint x;
    GVariantIter iter;

    g_print ("Inside Parse\n");

    g_variant_get (value, "((yu)y@a(ysb((sss)(sss))))", &ch1, &x, &ch2, &list);
    g_variant_iter_init (&iter, list); 
    while (g_variant_iter_loop (&iter, "(ysb((sss)(sss)))", &ch3, &str1, &bool1, &str2, &str3, &str4, &str5, &str6, &str7))
    {
        g_print ("%s\n", str1);
    }
    g_variant_unref(list);
}

int main()
{
    GVariantBuilder * builder = g_variant_builder_new (G_VARIANT_TYPE ("a(ysb((sss)(sss)))"));
    g_variant_builder_add (builder, "(ysb((sss)(sss)))", 'J', "Test1", TRUE, "Hn", "di", "hedfs", "dd", "dr", "hdf");
    g_variant_builder_add (builder, "(ysb((sss)(sss)))", 'J', "Test2", TRUE, "Hn", "di", "hedfs", "dd", "dr", "hdf");

    GVariant * result = g_variant_new ("((yu)ya(ysb((sss)(sss))))", 'R', 23, 'E', builder);

    g_variant_builder_unref (builder);
    ParseVariant (result);
}