Search code examples
cglibdbus

Send array of struct containing an array over DBus using glib


I am trying to send an array of this struct to a DBus Server:

typedef struct
{
    guint arg1;
    guchar msg[DTC_ACTION_PATH_LENGTH];
} DTC_ErrorMessage;

Here is the function I am working on:

gint fillMessage(GPtrArray **msg, DTC_ErrorMessage *data)
{
    g_assert(NULL != msg);
    g_assert(NULL == *msg);
    g_assert(NULL != data);

    *msg = g_ptr_array_new();
    g_assert(NULL != *msg);

    GValueArray *container = g_value_array_new(2); // struct of 2 elements
GValue v;

    memset(&v, 0, sizeof(GValue));

    // Insert first element of the struct
    g_value_init(&v, G_TYPE_INT);
    g_value_set_int(&v, data->arg1);
    g_value_array_append(container, &v);
    g_value_unset(&v);

    // Add code here for the second element of the struct

    g_ptr_array_add(*msg, (gpointer) container);

    return 0;
}

The questions are:

  • Is this the correct way to send complex structures over DBus? Because it seems very "intricate" to me.
  • How can I complete this function in order to add the second element of the struct?

Solution

  • This solution seems to work:

    gint fillMessage(GPtrArray **msg, DTC_ErrorMessage *data)
    {
        g_assert(NULL != msg);
        g_assert(NULL == *msg);
        g_assert(NULL != data);
    
        *msg = g_ptr_array_new();
        g_assert(NULL != *msg);
    
        GValueArray *vals;
        GArray *garray;
    
        vals = g_value_array_new(2);
    
        g_value_array_append(vals, NULL);
        g_value_init(g_value_array_get_nth(vals, 0), G_TYPE_UINT);
        g_value_set_uint(g_value_array_get_nth(vals, 0), data->arg1);
    
        garray = g_array_new(FALSE, TRUE, sizeof(guchar));
        gint i;
        for(i = 0; i < DTC_ACTION_PATH_LENGTH; i++)
        {
            g_array_append_val(garray, data->msg[i]);
        }
    
        g_value_array_append(vals, NULL);
        g_value_init (g_value_array_get_nth(vals, 1), dbus_g_type_get_collection ("GArray", G_TYPE_UCHAR));
        g_value_take_boxed (g_value_array_get_nth(vals, 1), garray);
    
        g_ptr_array_add(*msg, vals);
    
        return 0;
    }
    

    Any better solution would be appreciated!