2017-10-13 267 views
0

我目前嘗試與dbus進行通信並且有函數,該函數將返回array of struct(string, uint32, string, string, object path)。我將結果存儲在GVariant中,並打印此GVariant表明其中存在正確的結果值。獲取GVariant的內容

更具描述性:我嘗試獲取Systemd的Logind管理器ListSessions的結果。

打印的輸出是:

[('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」作爲價值?

回答

0
::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