简体   繁体   中英

Using void pointers in function signarture

I've recently inherited some (undocumented) C code that contains several instances of this pattern:

void my_function(void *_foo, const void *_bar) {
    MyType *foo = (MyType *)_foo;
    MyType *bar = (MyType *)_bar;

I'm pretty familiar with C but I can't for the life of me figure out why the function consumes void pointers. Isn't this just going to suppress potentially helpful compiler warnings if the wrong type is passed in anywhere? Or is there a sensible method behind it that I am new to?

Generally, the void * is used as an abstraction ie you can pass pointers of different types using void * to a function and later depending on appropriate conditions, you can typecast the void * to the correct type and use it.

Another usage could be when the calling function is in a logically separate unit like a library and doesn't have access to the correct type to which the pointer belongs. But, still the data has to pass through that function.

I used to use such abstraction mechanisms with callbacks. For Example, if I am calling a library which function which eventually calls my callback and I want some data of application in my callback, but, the library function has no use of it, then I will pass such data typecasted as void * to the library function and on receiving that data in the callback, I will typecast it to appropriate type and use it.

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