I want to add elements to a GSList
, that’s residing within a GValue
as a boxed type
. I.e. I’m searching for a function, that would simply replace the current value of GValue
- nothing more.
The following function don’t work]
-
take_boxed
will remove appended items of list (i.e. free current value insideGValue
) -
set_boxed
will copy the whole list -
set_static_boxed
will prevent freeing of list ong_value_unset
Is there any way to achieve, what I’m trying to do?
Example extract
GValue * gvalue = g_new0 (GValue, 1);
g_value_init (gvalue, TYPE_BOXED_SLIST_OF_GCHAR);
// Initialize to NULL
g_value_take_boxed (gvalue, NULL);
// 1nd Element
{
GSList * list = (GSList*)(g_value_get_boxed (gvalue));
list = g_slist_prepend (list, g_strdup("item1"));
g_value_take_boxed (gvalue, list);
// list size 1 now
}
//2nd Element
{
GSList * list = (GSList*)(g_value_get_boxed (gvalue));
g_slist_print (list, " ");
list = g_slist_prepend (list, g_strdup("item2"));
g_value_take_boxed (gvalue, list);
// `take` freed the first value; list size 1 now
}
// Show list size
{
GSList * list = (GSList*)(g_value_get_boxed (gvalue));
g_print ("list size: %d\n", g_slist_length (list));
// Actual output: 1
// Expected output: 2
}
g_value_unset (gvalue);
g_free (gvalue);
Full Example Code
#include <gtk/gtk.h>
void
g_slist_print(GSList *list,
const gchar *prefix)
{
g_print ("%slist (size:%d): ", prefix, g_slist_length (list));
while (list)
{
g_print ("%p, ", list);
list = list->next;
}
g_print ("\n");
}
void
boxed_slist_gchar_finalize(gpointer _self)
{
g_print (" boxed_slist_gchar_finalize\n");
GSList * self = (GSList*)_self;
if (NULL == self) return;
g_slist_free_full (self, g_free);
}
gpointer
boxed_copy_default(gpointer _self)
{
g_printerr ("ERROR: Boxed type does not support copying, but copy was called.\n");
return NULL;
}
#define TYPE_BOXED_SLIST_OF_GCHAR _TYPE_BOXED_SLIST_OF_GCHAR()
GType
_TYPE_BOXED_SLIST_OF_GCHAR()
{
static GType type;
if (!type)
type = g_boxed_type_register_static (
"type_boxed_slist_of_gchar",
boxed_copy_default,
boxed_slist_gchar_finalize);
return type;
}
int
main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
GValue * gvalue = g_new0 (GValue, 1);
g_value_init (gvalue, TYPE_BOXED_SLIST_OF_GCHAR);
g_value_take_boxed (gvalue, NULL);
g_print ("\n1nd Element:\n");
{
GSList * list = (GSList*)(g_value_get_boxed (gvalue));
g_slist_print (list, " ");
list = g_slist_append (list, g_strdup("item1"));
g_value_take_boxed (gvalue, list);
list = (GSList*)(g_value_get_boxed (gvalue));
g_slist_print (list, " ");
}
g_print ("\n2nd Element:\n");
{
GSList * list = (GSList*)(g_value_get_boxed (gvalue));
g_slist_print (list, " ");
list = g_slist_prepend (list, g_strdup("item2"));
g_value_take_boxed (gvalue, list);
list = (GSList*)(g_value_get_boxed (gvalue));
g_slist_print (list, " ");
}
g_value_unset (gvalue);
g_free (gvalue);
return 0;
}