简体   繁体   中英

Unsure of how to cast parameters of a function in C to void *

I am writing a generalized hashtable and I have created a typedef:

typedef unsigned long(*hashFunction_t)(void*,unsigned long);

That represents the hashing function.

I then use this in the function add:

int add(HashTable *table, hashFunction_t h, void *data);

However, I am getting a warning "initialization from incompatible pointer type" at the line:

hashFunction_t hash = JenkinsHash;

because JenkinsHash has the parameters:

unsigned long JenkinsHash(const char *str, unsigned long mod);

So my question is, how do I cast JenkinsHash to have the parameters:

(void*,unsigned long)

Thanks for the help!

The best way to do this without invoking undefined behavior is to make a new thunk function with the proper signature that performs the cast for you. The overhead will be minimal and you avoid a very unsafe typecast.

unsigned long JenkinsHashThunk(void *str, unsigned long mod)
{
    return JenkinsHash((const char*)str, mod);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM