我想編譯一個示例程序來使用lhash。我看不到有關lhash的好教程。所以,我理解lhash的唯一方法是使用lhash linux手冊頁。這是我正在嘗試的例子。但是,我在執行lh_insert時遇到了崩潰。我無能爲力,爲何會發生。lhsh在C中的lh_insert崩潰 - Linux?
/** In order to compile this program do the following **/
/** gcc lhastEx.c -lcrypto -o lhastEx.out **/
/** Install the openssl dev library on ubuntu by -- sudo apt-get install libssl-dev **/
/*** This is needed for library hash -- basically open ssl ones **/
#include <openssl/lhash.h>
/** Hash table -- just like maps in C++ i.e. QMAP -- it needs a key and the value **/
/*I have got a prints to check the flow */
#define __DBG (1)
static void dbgMsg(const char *msg)
{
#if __DBG
printf("%s",msg);
#endif
}
static int cmpFunc(const void *src, const void *dest)
{
dbgMsg("cmpFunc called..\r\n");
const int *obj1 = src;
const int *obj2 = dest;
return memcmp(obj1, obj2, sizeof(int));
}
static unsigned long keyHash(const void *entry)
{
unsigned long int hash = 0;
const int *val = entry;
dbgMsg("keyHash method invoked\r\n");
hash |= *(val);
return hash;
}
int main(int argc, char *argv[])
{
int *hashKey2 = malloc(sizeof(int));
int *hashKey3 = malloc(sizeof(int));
int *hashKey1 = malloc(sizeof(int));
*hashKey1 = 10;
*hashKey2 = 20;
*hashKey3 = 30;
/* we can make a function to generate this key unique **/
/** Ideally, this 1 should be a unique hash value **/
/************** Created the hash table now -- I see this as equivalent to the map in C++ or QtMap **/
LHASH_OF(int) *hashtable = lh_new(keyHash, cmpFunc);
/*** add a new entry now **/
lh_insert(hashtable, hashKey2);
return 0;
}
很高興看到你,你找到了一種方法。請注意,這存在與此相關的風險:您基本上使用散列表的「無類型」版本。這意味着編譯器不會阻止您將錯誤的類型變量插入到表中。如果你有興趣,如果你想做一個強類型的版本,我已經包含了一個答案。 –