获取 GVariant 的内容
Posted
技术标签:
【中文标题】获取 GVariant 的内容【英文标题】:Get the contents of GVariant 【发布时间】:2018-03-25 09:40:07 【问题描述】:我目前正在尝试与 dbus 通信并有一个函数,它将返回 array of struct(string, uint32, string, string, object path)
。我将结果存储在GVariant
中,打印此GVariant
表明那里有正确的结果值。
更具描述性:我尝试获取 Systemd 的 Logind Managers ListSessions
的结果。
print的输出是:
[('2', uint32 1000, 'nidhoegger', 'seat0', objectpath
'/org/freedesktop/login1/session/_32'), ('6', 1001, 'test', 'seat0',
'/org/freedesktop/login1/session/_36'), ('c2', 111, 'lightdm',
'seat0', '/org/freedesktop/login1/session/c2')]
我现在正在尝试使用以下方法在循环中获取每个数组元素:
for (uint32_t i = 0; i < ::g_variant_n_children(v); ++i)
GVariant *child = ::g_variant_get_child_value(v, i);
打印我得到的孩子时:
<('2', uint32 1000, 'nidhoegger', 'seat0', objectpath '/org/freedesktop/login1/session/_32')>
到目前为止一切顺利。现在我正在尝试以这种方式使用g_variant_get
获取单个项目:
gchar *id = NULL;
uint32_t uid = 0;
gchar *user = NULL;
gchar *seat = NULL;
gchar *session_path = NULL;
::g_variant_get(v, "(susso)", &id, &uid, &user, &seat, &session_path);
但它只给了我这个断言:
(process:12712): GLib-CRITICAL **: the GVariant format string '(susso)' has a type of '(susso)' but the given value has a type of 'v'
(process:12712): GLib-CRITICAL **: g_variant_get_va: assertion 'valid_format_string (format_string, !endptr, value)' failed
如果这是相关的:我生成了与gdbus-codegen
通信的代码,并且获取值的函数具有此签名:
gboolean login1_manager_call_list_sessions_sync (
Login1Manager *proxy,
GVariant **out_unnamed_arg0,
GCancellable *cancellable,
GError **error);
我做错了什么?为什么它返回“v”作为值?
【问题讨论】:
【参考方案1】:::g_variant_get(v, "(susso)", &id, &uid, &user, &seat, &session_path);
这看起来很可疑。你应该打电话给child
,而不是v
。
以下 C 代码对我来说很好用:
/* gcc `pkg-config --cflags --libs glib-2.0` -o test test.c */
#include <glib.h>
int
main (void)
g_autoptr(GVariant) sessions = NULL;
sessions = g_variant_new_parsed ("[('2', uint32 1000, 'nidhoegger', 'seat0', objectpath '/org/freedesktop/login1/session/_32'), ('6', 1001, 'test', 'seat0', '/org/freedesktop/login1/session/_36'), ('c2', 111, 'lightdm', 'seat0', '/org/freedesktop/login1/session/c2')]");
for (gsize i = 0; i < g_variant_n_children (sessions); i++)
g_autoptr(GVariant) child = g_variant_get_child_value (sessions, i);
g_message ("Child %" G_GSIZE_FORMAT ": %s", i, g_variant_get_type_string (child));
guint32 uid;
const gchar *id, *user, *seat, *session_path;
g_variant_get (child, "(&su&s&s&o)", &id, &uid, &user, &seat, &session_path);
g_message ("%s, %u, %s, %s, %s", id, uid, user, seat, session_path);
return 0;
它打印以下内容:
** Message: Child 0: (susso)
** Message: 2, 1000, nidhoegger, seat0, /org/freedesktop/login1/session/_32
** Message: Child 1: (susso)
** Message: 6, 1001, test, seat0, /org/freedesktop/login1/session/_36
** Message: Child 2: (susso)
** Message: c2, 111, lightdm, seat0, /org/freedesktop/login1/session/c2
【讨论】:
以上是关于获取 GVariant 的内容的主要内容,如果未能解决你的问题,请参考以下文章