2

我正在尝试构建一个包含整数、time_t 和一些 char* 的结构实例的 GHashTable。

我的问题是,如何将结构的实例插入 GHashTable?有很多关于如何插入字符串或 int 的示例(分别使用 g_str_hash 和 g_int_hash),但我猜我想使用 g_direct_hash,但我似乎找不到任何示例。

理想情况下,我的代码如下所示:

GHashtable table;
table = g_hash_table_new(g_direct_hash, g_direct_equal);
struct mystruct;
mystruct.a = 1;
mystruct.b = "hello";
mystruct.c = 5;
mystruct.d = "test";

g_hash_table_insert(table,mystruct.a,mystruct);

显然,这是不正确的,因为它无法编译。谁能提供一个做我想做的事的例子?谢谢,里克

4

3 回答 3

2

您不能插入自动变量;您必须为数据分配内存以动态方式存储,即使用g_malloc()或等效方式。

然后,您需要找出一种从数据中计算哈希值的方法,以帮助表高效。在这里使用g_direct_hash()不是很好;它将使用指向您的数据的指针作为哈希值。

似乎您想使用a结构的成员作为键;这个字段是什么类型的?如果它是整数,则可以使用g_int_hash().

我认为这更符合您的实际代码应该是什么样的:

GHashtable *table;
struct mystruct *my;

table = g_hash_table_new_full(g_int_hash, g_int_equal, NULL, g_free);
my = g_malloc(sizeof *my);
my->a = 1;
my->b = "hello";
my->c = 5;
my->d = "test";

g_hash_table_insert(table, GINT_TO_POINTER(my->a), my);

请注意,这假设bandd成员只是字符指针,因为没有为字符串动态分配存储空间。

于 2010-04-19T12:09:34.540 回答
1

您必须在堆上分配结构,以便可以在哈希表中存储指针:

struct SomeType * p = malloc(sizeof(struct SomeType));
p->a = 1;
//etc..
g_hash_table_insert(table,p->a,p);

您还需要使用 g_hash_table_new_full() 以便在表被销毁时正确释放指针。

于 2010-04-19T12:07:44.577 回答
1

谢谢。上面的例子有所帮助。在阅读了这些并通过网络上的代码示例之后,我可以让它工作。以下是我编写的示例工作代码:


#include <stdio.h>
#include <glib.h>
#include <stdlib.h>

struct struct_process {
    int pid;
    char* file_to_process;
};

typedef struct struct_process Process;

int main() {
    GHashTable* hash_table = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, g_free);

    Process* p1 = (Process*)(malloc(sizeof(Process)));
    p1->pid = 1234;
    p1->file_to_process= "/var/tmp/p1";

    g_hash_table_insert(hash_table, GINT_TO_POINTER(p1->pid), GINT_TO_POINTER(p1));

    # replace 1234 by some other key to see that it returns NULL on nonexistent keys
    Process* p3 = (Process*)(g_hash_table_lookup(hash_table, GINT_TO_POINTER(1234))); 

    if (p3 == NULL) {
       printf("could not find\n");
    } else {
       printf("found and i have to process %s\n", p3->file_to_process);
    }
    g_hash_table_destroy(hash_table);
}
`
于 2010-10-31T07:28:05.070 回答