Reputation: 157
In an API, is there some advantage to using type void *
as a handle to structures returned to the user (as opposed to using type name_of_the_structure *
and just hiding the implementation)?
Upvotes: 1
Views: 152
Reputation: 409136
If you use void*
then the contents is a completely black box which the user can't know anything about. However you also loose some type safety, as the user of your API can pass any pointer to your function and you have no simple way of detecting if it's a correct pointer or not.
Fortunately, you don't actually have to completely hide the structure. You simply have a public header which is distributed with the API, which declares the structure, like
struct my_special_struct;
Then your functions can still be declared using pointers to that structure, and the user too, but the user have to use your functions do create the actual instances, and the user also can't use your structure to access internal fields or get its size using sizeof
.
Upvotes: 2