I recently wrote a wrapper for LevelDB in C and stumbled about the following problem. The LevelDB function to store data in a database looks like this:
leveldb_put(leveldb_t* db, const leveldb_writeoptions_t* options, const char* key, size_t keylen, const char* val, size_t vallen, char** errptr);
For the key and value, they use a char*
. That means I would have to cast arguments that aren't char
pointers. This happens often because I often store structs in the database.
After thinking about this I decided to use a void*
for key and data in my wrapper function. It then looks something like this:
int db_put(db_t db, void *key, size_t keylen, void *value, size_t valuelen)
{
char *k = (char*)key;
char *v = (char*)value;
/* Call leveldb_put() here with k and v as parameters. */
return 0;
}
This way I don't have to cast the arguments I pass to my db_put()
function. I think this solution is more elegant, but I guess LevelDB knew what they were doing when they choose the char
pointers.
Is there a reason not to use void*
to pass arbitrary data to a function?