2010-04-19 1 views
2

int, time_t 및 char *를 포함하는 구조체의 인스턴스로 GHashTable을 작성하려고합니다.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); 

분명히이가 컴파일되지 않는 올바르지 않습니다. 누구든지 내가 원하는대로 할 수있는 예를 제공 할 수 있습니까? 감사합니다, 릭

답변

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()를 사용해야합니다을 그래서 당신은 제대로 할 수 테이블이 파괴되면 포인터를 비우십시오.

2

자동 변수를 삽입 할 수 없습니다. g_malloc() 또는 이와 동등한 방법을 사용하여 데이터를 동적으로 저장하도록 메모리를 할당해야합니다.

그런 다음 테이블의 효율성을 높이기 위해 데이터에서 해시 값을 계산하는 방법을 찾아야합니다. g_direct_hash()을 사용하면 좋지 않습니다. 데이터에 대한 포인터를 해시 값으로 사용합니다.

구조체의 구성원 인 a을 키로 사용하려는 것처럼 보입니다. 이 필드는 어떤 유형입니까? 정수이면 g_int_hash()을 사용할 수 있습니다. 이것은 어떤 스토리지가 동적에 할당되지 않은 이후 bd 회원, 단순히 문자 포인터 있다고 가정

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); 

참고 :

나는이 실제 코드가 어떻게 보일지의 라인을 따라 더 생각 현.

+0

'테이블 = g_hash_table_new_full (g_int_hash, g_int_equal, NULL, g_free)' – ntd

+0

@ntd : 감사합니다, 고정! – unwind

+0

하나의 개선점은 g_malloc 대신 g_new (struct mystruct, 1)를 사용하는 것입니다. 두 가지 오류 원인을 제거합니다 (잘못된 크기 할당 및 잘못된 유형의 메모리 할당). –

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); 
} 
`