如何从 GHashTable 访问 gpointer 指向的 GString
C 代码
#include <glib.h>
//...
GHashTable *hash = g_hash_table_new(NULL, NULL);
GString val;
g_hash_table_insert(hash, (int*)5, g_string_new("Bar"));
val = g_hash_table_lookup(hash, (int*)5); // line 10
printf("Foo ~ %s\n", val->str); // line 16
if (NULL == val) // line 18
printf("Eet ees null!\n");
生成的
: <块引用>ctest.c:10:错误:赋值中的类型不兼容
ctest.c:16:错误:“->”的类型参数无效(有“GString”)
ctest.c:18:错误:二进制 == 的操作数无效(具有“void *”和“GString”)
我做错了什么? :(
编辑:有些人可能会感到困惑,并问自己“她为什么不使用 g_string_printf()
?”
因为我需要访问 gchar *str< /code>,打印只是我“调试”它的方式
:添加了第 18 行,并对那些令人惊叹的行进行了注释(是的,到处都是空白。我是可怕,我知道)。
The C code
#include <glib.h>
//...
GHashTable *hash = g_hash_table_new(NULL, NULL);
GString val;
g_hash_table_insert(hash, (int*)5, g_string_new("Bar"));
val = g_hash_table_lookup(hash, (int*)5); // line 10
printf("Foo ~ %s\n", val->str); // line 16
if (NULL == val) // line 18
printf("Eet ees null!\n");
Which produced:
ctest.c:10: error: incompatible types in assignment
ctest.c:16: error: invalid type argument of '->' (have 'GString')
ctest.c:18: error: invalid operands to binary == (have 'void *' and 'GString')
What am I doing wrong? :(
EDIT: Some might be confused and ask ask themselves "Why didn't she use g_string_printf()
?"
Because I need to access gchar *str
, printing was just my way of "debugging" it.
EDIT: Added line 18, and commented the spazzing lines (yes, lots of whites-paces all over the place. I'm dreadful, I know).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
函数
g_string_new
返回一个GString *
。这就是存储在哈希中的内容。函数g_hash_table_lookup
返回一个void *
。你可能想要这样的东西:The function
g_string_new
returns aGString *
. So that's what's getting stored in the hash. And the functiong_hash_table_lookup
returns avoid *
. You likely want something like this:GString 结构声明为:
因此要访问字符串只需使用
.
运算符:同时将
(int*) 5
作为参数传递给函数可能是错误的。这会将整数值5
转换为指针。但您想要的是一个指向int
的指针,其中int
值为 5。为此,您可以使用复合文字:
&(int) {5}
或使用指向int
类型对象的指针:A GString structure is declared as:
so to access the string just use the
.
operator:Also passing
(int*) 5
as an argument to your function is probably wrong. This converts the integer value5
to a pointer. But what you want is a pointer to anint
where theint
value is 5.To do this you can either use a compound literal:
&(int) {5}
or use a pointer to an object of typeint
:val->str
应该是val.str
- 它不是一个指针。这也意味着您不能执行if (NULL == val)
。val->str
should beval.str
- it's not a pointer. This also means you can't doif (NULL == val)
.