c - GLib:哈希表无法正确找到值

标签 c string hashtable glib assimp

所以我最近一直在使用GLib的类型,例如列表和映射,但是遇到了一个相当麻烦的问题。

首先,我创建了我的哈希表:

BoneIdMap = g_hash_table_new(g_direct_hash, g_str_equal);

然后我尝试一下,在字符串键处插入一些 uint,它工作得很好:

char* string = alloq_calloc(&model->dynamic, strlen(aimesh->mBones[x]->mName.data) + 1, sizeof(char));
strcpy(string, aimesh->mBones[x]->mName.
if(map_find(&model->BoneIdMap, string, &handle)) {
    index = *handle;
} else {
    index = model->BoneIdMap.size;
}
map_insert(&model->BoneIdMap, &index, sizeof(uint), string);

请注意:我动态分配指针,那是因为我尝试仅传递静态数组,但它不起作用(结果两者都不起作用)

然后我继续尝试稍后检索这些 uint:

char* string = alloq_calloc(&model->dynamic, strlen(ainode->mName.data) + 1, sizeof(char));
strcpy(string, ainode->mName.data);
/* Time to do some debugging */
if(map_find(&model->BoneIdMap, string, &handle)) {

但它根本不起作用...我尝试将所有键检索到一个数组中:

uint len;
char** arr = g_hash_table_get_keys_as_array(model->BoneIdMap.table, &len);
for(int i = 0; i < len; ++i) {
   if(arr[i]) printf("Key: %s\n", arr[i]);
       if(!strcmp(arr[i], ainode->mName.data)) printf("Yes!\n");
}
printf("----------------------------\n");

而且它有效! (???)

Key: pelvis
Key: toe.L
Yes!
Key: sheath
Key: lamp
----------------------------
Key: toe.R
Key: shin.L
Key: fingerstip.R
Key: neck
Key: thigh.R
Key: fingers.L
Key: shin.R
Key: spine
Key: lamp
Key: head
Key: fingerstip.L
Key: thm_end.L
Key: thm_end.R
Key: tiptoe.L
Yes!
Key: upperarm.R

请注意,如果我除了上面的打印功能之外还使用静态字符串添加一个键并尝试找到它,它会起作用! 这让我很困惑......

顺便说一下,mName 是一个 aiString (ASSIMP) --

Public Attributes
char    data [MAXLEN]
    String buffer.
size_t  length
    Binary length of the string excluding the terminal 0.

感谢您的阅读...

最佳答案

您正在使用 g_direct_hash 哈希函数,该函数旨在用于字符串键的 gpointer,请尝试将其更改为 g_str_hash

// g_direct_hash implementation seems to be this
guint
g_direct_hash (gconstpointer v)
{
  return GPOINTER_TO_UINT (v);
}
至于为什么它与静态字符串文字一起工作,我想说它是编译器针对二进制空间进行优化并将两个具有相同内容的文字折叠到单个数据段记录中,因此它散列相同的指针,这就是它看起来有效的原因正确,尽管事实并非如此。

关于c - GLib:哈希表无法正确找到值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44832822/

相关文章:

c - gdb 断点在错误的行号中命中

C-程序: Memory overflow for hash table using array of linked lists

c - GCC,链接库,找不到?

string - 公式来查看姓氏是否在单元格内重复并输出简化的字符串

javascript - 为什么添加 "{" "}"会从数组中删除括号? (JavaScript)

python - 为什么 Python "".split() 和 "".split (",") 会产生不同的结果?

c# - 只寻找现有变量

c - Glib HashTable 未正确插入

c - 修复 C 中的边界问题

c++ - 如何使用 pthread_setaffinity_np