So, normally we typedef to another type or function pointer, but typedef a type to a pointer is strange to me. For example, in winnt.h we got:
typedef void *HANDLE;
typedef PVOID HANDLE;
and PVOID is:
typedef void *PVOID,*LPVOID;
According to that, in the first statement it must be *HANDLE because it's a pointer to void, while PVOID is already a pointer to void, therefore it needs not to be declare as a pointer.
However, what's the benefit of typedef a type to a pointer? Isn't it more confusing?
A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function.
h> void upton(int n) { for (int i = 1; i <= n; ++i) printf("%d\n", i); } void nth(int n) { printf("%d\n, n); } Notice they both are having similar signature. So we can create function pointer which would be able to point both the functions . It can be done by the method given below.
Typedef cannot be used to change the meaning of an existing type name (including a typedef-name). Once declared, a typedef-name may only be redeclared to refer to the same type again.
The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands.
what's the benefit of typedef a type to a pointer? Isn't it more confusing?
Usually, modules/Libraries need to maintain some internal state for their proper functioning. This internal state needs to be read/verified on every api that is called for this module/library. So the user of the module needs to pass this information to every api they call. But the library implementor do not want that the users of the library be able to see the contents of this maintained statem, because if they are allowed to, someone might play mischief or make honest mitake of modifying the state, and the results of that might be drastic for the module. To avoid such an scenario the modules mask their state maintiaining variables as a void*
so that now it is opaque(it's contents are not visible) to users of the module. For benifit of letting the users not being confused about using void *
they usually typedef the void *
as HANDLE
, this is for ease of usage for the clients of the module/library.
As for the mentioned code:
typedef void *PVOID,*LPVOID;
means wherever you mention PVOID
henceforth it will be treated as a void *
type.
So in,
typedef PVOID HANDLE;
is equivalent to:
typedef void *HANDLE;
Because PVOID
is nothing but void *
.
And if you are curious why to use 2 typedefs for the same value, the answer is: they have different meaning and use cases. HANDLE is a handle to an object and PVOID is just pointer to any type. So it's just for better readability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With