Adding custom structure to GSList with Glib

北城余情 提交于 2019-12-24 05:46:08

问题


I'm trying to add a structure to a singly linked list with the function g_slist_append(list, &structure). This seems to work (it's adding the pointer), however I can't seem to find a way to view the elements in the structure when reading the linked list.

My structure looks like this:

 struct customstruct
 {
   int var1;
   int var2;
   char *string_1;
 }

Then, I make a list: GSList *list = NULL;

Then, I append one instance of the structure like this:

 struct customstruct list_entry;
 list_entry.var1 = 1;
 list_entry.var2 = 2;
 list_entry.string_1 = "String";

 list = g_slist_append(list, &entry);

 printf("Entry var1 = %d\n", list->data->var1);

That last line fails because var1 can't be found (request for member in something not a struct or union).

I think I need to cast it to the right type but I don't know how. Anyone?


回答1:


I'm guessing the data member of the GSList structure is a void pointer, i.e. a pointer that can point to anything but doesn't have any other type info.

This means you have to use type-casting:

((struct customstruct *) list->data)->var1


来源:https://stackoverflow.com/questions/14561108/adding-custom-structure-to-gslist-with-glib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!