glib g_hash_*() using strings as key



This is my second app that uses the glib hash function.  My first one
worked OK.  I allocated a big glob of memory in my main to store the
keys and values.  The catch is that I didn't expect that hash to grow
any after the initial startup.  With my second g_hash app, I know the
hash will change size.  So, I am trying to dynamically allocate memory
on the fly.  My hash is not so dynamic that it has to add and remove
elements one at a time.  Basically, I will get a signal that says to
re-load the hash.

In my main, I declare a GHashTable *byevent and initilize it with
g_hash_table_new(g_str_hash, g_str_equal).  Assuming I get a valid
pointer back, I then call my function that loads the hash.  Here is
pseudo-code of what it looks like:

int pud_get_events(GHashTable *table) {
        /* this just calls free() on the data */
        g_hash_table_foreach(table, pud_free_event, NULL);
        foreach event_struct (select records from database) {
                (event_struct *)pevent = NULL;
                pevent = (event_struct *)malloc(sizeof(event_struct));
                copy event from database to pevent
                g_hash_table_insert(table, pevent->evt_name, pevent);
        }
        return
}

As you can see, the value of my hash table is a data structure and the
key is one of the members of the data structure.  This appears to work
fine.  In fact, later on in my main I call
g_hash_table_foreach(byevent, pud_print_events, NULL).  My
pud_print_events function gets called the corred number of times with
the correct data.

Here's the catch:  when I call g_hash_table_lookup(byevent,"some key
text") I always get NULL back.  As an ugly hack, I can call
g_hash_table_foreach with the key to be looked up perform a strcmp in
the callback function and find my event.  This, of course, negates the
elegance of a hash.

BTW, my system is SunOS nfmdev 5.5.1 Generic_103640-21 sun4u sparc
sun4u running Glib 1.2.6 compiled with gcc 2.8.1.
-- 
 (__)  Doug Alcorn          | program == list of computer instructions
 oo /  doug@lathi.net       | firmware == program that is not user modifiable
 |_/   http://www.lathi.net | software == program that a user can modify
       Cincinnati, OH       | "If you don't have the source, it's not software"



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]