简体   繁体   English

使用Glib向GSList添加自定义结构

[英]Adding custom structure to GSList with Glib

I'm trying to add a structure to a singly linked list with the function g_slist_append(list, &structure). 我正在尝试使用函数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; 然后,我列出一个列表: 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). 最后一行失败,因为无法找到var1 (请求成员不是结构或联合)。

I think I need to cast it to the right type but I don't know how. 我想我需要把它投到正确的类型,但我不知道如何。 Anyone? 任何人?

I'm guessing the data member of the GSList structure is a void pointer, ie a pointer that can point to anything but doesn't have any other type info. 我猜测GSList结构的data成员是一个void指针,即一个可以指向任何东西但没有任何其他类型信息的指针。

This means you have to use type-casting: 这意味着你必须使用类型转换:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM