May I know the usage and logic behind the opaque pointer concept in C?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
An opaque pointer is one in which no details are revealed of the underlying data (from a dictionary definition: opaque: adjective; not able to be seen through; not transparent).
For example, you may declare in a header file (this is from some of my actual code):
which declares a type
pmpiwhich is a pointer to the opaque structurestruct pmpi_s, hence anything you declare aspmpiwill be an opaque pointer.Users of that declaration can freely write code like:
without knowing the actual “definition” of the structure.
Then, in the code that knows about the definition (ie, the code providing the functionality for
pmpihandling, you can “define” the structure:and easily access the individual fields of it, something that users of the header file cannot do.
More information can be found on the Wikipedia page for opaque pointers..
The main use of it is to hide implementation details from users of your library. Encapsulation (despite what the C++ crowd will tell you) has been around for a long time 🙂
You want to publish just enough details on your library for users to effectively make use of it, and no more. Publishing more gives users details that they may come to rely upon (such as the fact the size variable
szis at a specific location in the structure, which may lead them to bypass your controls and manipulate it directly.Then you’ll find your customers complaining bitterly when you change the internals. Without that structure information, your API is limited only to what you provide and your freedom of action regarding the internals is maintained.