在ghash.c 中查看g_int64_hash 和g_int64_equal 是如何实现的:
...
gboolean
g_int64_equal (gconstpointer v1,
gconstpointer v2)
{
return *((const gint64*) v1) == *((const gint64*) v2);
}
...
guint
g_int64_hash (gconstpointer v)
{
return (guint) *(const gint64*) v;
}
...
你可以写你赢的uint64_t_hash和uint64_equal类似:
gboolean
uint64_t_equal (gconstpointer v1,
gconstpointer v2)
{
return *((const uint64_t*) v1) == *((const uint64_t*) v2);
}
guint
uint64_t_hash (gconstpointer v)
{
return (guint) *(const uint64_t*) v;
}
看一个例子:
#include <glib.h>
#include <stdio.h>
#include <inttypes.h>
/* the value structure */
typedef struct __MyStruct
{
int a;
int b;
} MyStruct;
/* the hash equality function */
static gboolean
uint64_t_equal (gconstpointer v1,
gconstpointer v2)
{
return *((const uint64_t*) v1) == *((const uint64_t*) v2);
}
/* the hash function */
static guint
uint64_t_hash (gconstpointer v)
{
return (guint) *(const uint64_t*) v;
}
/* the hash function */
static void
print_hash(gpointer key,
gpointer value,
gpointer user_data)
{
printf("%" PRIu64 " = {%d, %d}\n",
*(uint64_t*) key, ((MyStruct *) value)->a, ((MyStruct *) value)->b);
}
int
main(int argc, char **argv)
{
GHashTable *hash;
/* key => value */
uint64_t k1 = 11; MyStruct s1 = {1, 11};
uint64_t k2 = 22; MyStruct s2 = {2, 22};
uint64_t k3 = 33; MyStruct s3 = {3, 33};
hash = g_hash_table_new(uint64_t_hash, uint64_t_equal);
/* insert values */
g_hash_table_insert(hash, &k1, &s1);
g_hash_table_insert(hash, &k2, &s2);
g_hash_table_insert(hash, &k3, &s3);
/* iterate over the values in the hash table */
g_hash_table_foreach(hash, print_hash, NULL);
g_hash_table_destroy(hash);
return 0;
}