I want my GValue
to contain and own a dynamic string (gchar*
). It should clean up the string (gchar*
) on termination.
I'm trying to use a Boxed Type
, but I can't get it to work.
This is what I've got so far:
GType boxedString = g_boxed_type_register_static (
"boxedString", boxed_copy, boxed_free);
GValue * val = g_new0(GValue, 1);
g_value_init (val, boxedString);
g_value_take_string (val, g_strdup ("hello"));
But that throws a g_value_take_string: assertion 'G_VALUE_HOLDS_STRING (value)' failed
.
g_value_take_string
: Doesn't work. String is not owned and therefore not freed.GValue * val = g_new0(GValue, 1);
g_value_init (val, G_TYPE_STRING);
g_value_take_string (val, g_strdup ("hello"));
G_TYPE_STRING
: Doesn't work. String is not owned and therefore not freed.GObject
, that can hold a pointer and a destruction method, it would work. But I can't find any type that allows it.The string won’t be freed until you call g_value_unset()
.
GValue *val = g_new0 (GValue, 1); // you can also stack-allocate it to avoid a call to g_new0()
g_value_init (val, G_TYPE_STRING);
g_value_set_string (val, "hello");
// or g_value_take_string (val, g_strdup ("hello"));
…
g_value_unset (val);
g_free (val);