简体   繁体   中英

Why do hiredis functions use void* instead of redisReply*?

I am new to hiredis and use v0.13. I noticed that the API functions from hiredis.h , which deal with redisReply* objects, all use void* . For example,

void *redisCommand(redisContext *c, const char *format, ...);

returns a redisReply* object (or NULL );

int redisGetReply(redisContext *c, void **reply);

outputs a redisReply* object through reply ;

void freeReplyObject(void *reply);

is, according to the code comment, a “Function to free the reply objects hiredis returns by default.”

What am I missing here—why do these functions use void* instead of redisReply* ?

I noticed that the API functions from hiredis.h , which deal with redisReply* objects, all use void*

The only sensible way I can see to interpret your description is that you've analyzed the implementation to find that internally , it uses pointers to a type named redisReply , but the interface deals with such pointers via type void * instead.

That would be a mechanism for forcing clients of that API to handle the reply object pointers as opaque values . Clients (presumably) don't have have the definition of redisReply , or even its name, and there is no declared association between the reply pointers and that type, so the API explicitly avoids providing a way for clients to create such objects or interpret or modify their values other than via the API's own functions. All they can do is receive those opaque pointers from the API and pass them back.

I will also say, however, that this particular approach to opaque pointers is a poor one. It is possible to provide much better type safety without giving up opacity, as demonstrated in the answer to the question linked above.

Generic functions are written often this way as you can cast any pointer to void * and void * to the same pointer (same about the char pointer types) without the risk and portable. You also will not get any compiler warnings.

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