以下是我可以创建的问题的最短的可编辑演示。
查看结尾附近的printf
电话,输出如下。我不知道为什么完全相同的两个语句可能会这样做。它可能与输入类型有关,但我看不出它可能是什么。
#include <gtk/gtk.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
int
main (int argc, char *argv[])
{
gtk_init (&argc, &argv);
GtkBuilder * builder = gtk_builder_new ();
GHashTable * table = g_hash_table_new(NULL,NULL);
int i;
char builderdoc[] = "<?xml version=\"1.0\"?>"
"<interface>"
" <requires lib=\"gtk+\" version=\"2.16\"/>"
" <!-- interface-naming-policy project-wide -->"
" <object class=\"GtkCheckButton\" id=\"checkbutton1\">"
" </object>"
"</interface>";
// Load gtkbuilder
gtk_builder_add_from_string (builder, builderdoc, sizeof(builderdoc),NULL);
char * buffer[][2] = {
{"log","checkbutton1"}
};
// Load array of widgets into hash table (Shortened)
for(i = 0; i < sizeof(buffer) / sizeof(char *) / 2; i++){
g_hash_table_insert(table,(gchar *) buffer[i][0],gtk_builder_get_object (builder, (gchar *) buffer[i][1]));
}
// Load xml doc
xmlDocPtr doc;
xmlNodePtr cur;
xmlNodePtr cur2;
char xmldoc[] = "<?xml version=\"1.0\"?>"
"<CsSettings>"
"<options>"
"<check name=\"log\" value=\"1\" />"
"</options>"
"</CsSettings>";
doc = xmlParseMemory(xmldoc, (int) sizeof(xmldoc));
cur = xmlDocGetRootElement(doc);
cur = cur->xmlChildrenNode;
// Find what we're looking for
while (cur != NULL){
if(xmlStrEqual(cur->name, (xmlChar *) "options")){
cur2 = cur->xmlChildrenNode;
while (cur2 != NULL){
if(xmlStrEqual(cur2->name, (xmlChar *) "check")){
// We've found it, now print some output
printf("Plain old lookup: g_hash_table_lookup(table,\"log\"): %p\n",g_hash_table_lookup(table,"log"));
printf("Variable lookup : g_hash_table_lookup(table,\"%s\"): %p\n",(gchar *) xmlGetProp(cur2, (xmlChar *) "name"),g_hash_table_lookup(table,(gchar *) xmlGetProp(cur2, (xmlChar *) "name")));
printf("Xml says we should lookup: '%s'\n",(gchar *) xmlGetProp(cur2, (xmlChar *) "name"));
}
cur2 = cur2->next;
}
}
cur = cur->next;
}
}
令人眼花缭乱的输出:
Plain old lookup: g_hash_table_lookup(table,"log"): 0x1e369a0
Variable lookup : g_hash_table_lookup(table,"log"): (nil)
Xml says we should lookup: 'log'
答案 0 :(得分:3)
您可能会从哈希表中获得意外行为,因为您没有在构造函数上设置任何哈希或相等的函数,在这种情况下,对g_direct_hash()
和g_direct_equal()
函数的指针进行直接哈希处理
如果表格的密钥为gchar *
,我会使用g_str_hash
和g_str_equal
。这样的东西可以用来创建你的桌子:
GHashTable * table = g_hash_table_new(g_str_hash,g_str_equal);
如果哈希表的键是指针指向的内容,则指针上的直接哈希不是一个好主意。请告诉我们这是否解决了这个问题。