Search code examples
cfunction-pointers

How to accept pointer to a function with any number of parameters, as a parameter in C and call it?


I'm building a hashmap API. In that API, I have a hashmap_new() function that creates a new hashmap (acts like a constructor). I want the user to be able to specify be able to supply pointer to their own hash function as an argument to hashmap_new().

The problem I'm facing is that this user-defined hash function can have any number of arguments and that too in any order. For instance: some hash functions require only the data as an argument, some require data and length, while others require data, length and seed(s).

My code looks something like this:

struct hashmap *hashmap_new(int capacity, uint64_t (*hash_fn)(const void *key, uint64_t len))
{
  ... // code for allocation and setting other variables
  map->hash_fn = hash_fn;

  return map;
}

After setting the hash function for my map, I want to call it from other parts of my code wherever required. How can I write hashmap_new() function that accepts a pointer to hash function that accepts any number of arguments and how can i call that function with that many number of arguments?


Solution

  • Declare your hash functions to take a single void * argument. Then for each function, define a struct that contains the parameters for that hash, and inside the function convert the void * to a pointer to the appropriate struct type.

    Later when you call the hash function, populate an instance of the appropriate struct and pass a pointer to that struct to the function.