void* In fact can be understood as a context, using it can be very good to achieve C Language Object-oriented programming . I think the use of void*, not to look good, but a convention, the people who are programmed by C + + can see void*, and habitually think that-this is a private data that only the defined party has the right to interpret; and that's what we pass in the callback function void* As the basic consensus of UserData.
void*
pointer can actually be used as a generic, you imagine you want to exchange two variables in C, if it is two integers, it is like:
void swap_int(int* lhs, int* rhs){ int tmp = *lhs; *lhs = *rhs; *rhs = tmp;}
If you want to swap decimals, write a
void swap_float (float * lhs, float * RHS) {; //}
So since you're swapping the bit pattern of two variables, you can abstract this approach:
void swap ( void * lsh, void * RHS) {; //}
Because you don't know exactly how many bits to swap, you also need a parameter to specify the number of bits to swap:
void swap ( void * lsh, void * RHS, size_t size) {; //}
with such a function, if you want to exchange two variables, you can:
swap (&ai, &bi, sizeof (int )); Swap (&AF, &BF, sizeof ( float ));
Using void* just to "look" logical
But, with the example back above, if I usefloat*
Replacevoid*
, that's okay, but why should I do it every time I call it? Coercion type conversionswap((float* )&ai, (float* )&bi, sizeof(int))
, what would he think if you used such an interface for another person? I wipe, you swap two integers, and you first convert tofloat*
, in case of a novice, they still do not dare to use, I rub, you this inside what is the secret?
Indeed, void*
, like any other pointer, is a memory space of the same size, and the only difference to the other pointers is that you cannot void*
to dereference, it seems that other types of pointers can be void*
instead, just convert it to the appropriate type of pointer before the dereference is OK!
Well, if that's the case, it void*
's really meant to look logical. I can't think of any situation that must be used void*
!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
What is the use of void* pointers?