Search code examples
chashtableglib

How can i use longs as key in glib hash table?


in g_hash_table_new(HashFunc hash_func, GEqualFunc key_equal_func)

HashFunc they have this types:

  • g_direct_hash()
  • g_int_hash()
  • g_int64_hash()
  • g_double_hash()
  • g_str_hash()

GEqualFunc they have this types:

  • g_direct_equal()
  • g_int_equal()
  • g_int64_equal()
  • g_double_equal()
  • g_str_equal()

Which type can i use to have a key that is a long and a value that is a pointer for a struct that i have defined?


Solution

  • Summarizing from comments:

    Assuming you build for a system where a pointer is at least as many bits as a long (true on most systems), yes, you can cast it to a gconstpointer and use g_direct_*. You do build in a dependency on that fact into your code that way though.

    Otherwise: do not use long but either gint or gint64 for your values and pass pointers to them to g_int_* or g_int64_*. Using long, which can differ in actual size per system, in portable code is not handy anyway.

    g_direct_* use the pointers themselves instead of the values pointed to by them.