Dienstag, 10. September 2013

Initializing a Glib2 String Hash-Map

Glib2 is a big help while working with native C. I had some hard time using a key/ value hash map ( in GLib2 it is called "hashtable") for strings.
My naive, lazy appoach was this one:
// this outputs "NULL"
#include <glib.h> 

void testHashMap( const char* key, const char* value ) {

    GHashTable* test = g_hash_table_new( NULL, NULL );
    g_hash_table_insert ( test , g_strdup(key),  g_strdup(value) );

    char * result = g_hash_table_lookup( test,  "mykey" );

    printf("found %s\n", result );
}

int main() {
    testHashMap( "mykey", "myval");
}
As you can see I didn't really bother with the parameters of g_hash_table_new since I assumed that it would choose the correct hash function (first parameter) and the correct compare function (parameter two) automatically.

No, it doesn't. Reading the manual about the function it reveals that the NULL behaviour is all about working with pure pointers. To let the hash table work with strings as expected, the hash function g_str_hash and the compare function g_str_equal need to be supplied. 

This concludes in the following, now working code:
// this outputs "myval" as expected
#include <glib.h>

void testHashMap( const char* key, const char* value ) {

    GHashTable* test = g_hash_table_new( g_str_hash, g_str_equal );
    g_hash_table_insert ( test , g_strdup(key),  g_strdup(value) );

    char * result = g_hash_table_lookup( test,  "mykey" );

    printf("found %s\n", result );
}

int main() {
    testHashMap( "mykey", "myval");
}

Keine Kommentare:

Kommentar veröffentlichen