Search code examples
ctypedefencapsulationopaque-pointers

Using an opaque pointer to a non struct type


In my C programming, I use opaque-pointers to struct as a way to enforce abstraction and encapsulation of my code, in that manner :

interface_header.h:

 typedef struct s_mytype t_mytype;

defs_header.h:

struct s_mytype
{
/* Actual definition of the struct */
};

My problem I want to use a simple type as t_mytype (char for example), but not inform the interface about that. I can't just use typedef char t_mytype, since that would expose the the internals of the type. I could just use void pointers, but at the cost of type-checking, and I'd rather avoid that.

Doing two typedef wont work either, since that throw an typedef redefinition with different types from the compiler.

I am also considering doing a struct with only one member, which will be my simple type, but would that be an overkill ?

Thanks for your answers.


Solution

  • You have to make a decision. With code like this:

    typedef char myHandle;
    
    frobnicate(myHandle *obj);
    

    you already document the intent that client code should only use pointers to myHandle and never assume anything about the underlying type, so you should be able to change the typedef later -- unless there's "sloppy" client code making assumptions it shouldn't.


    If you want to completely hide what's behind myHandle, a struct is your only option in C:

    typedef struct myHandle myHandle;
    
    frobnicate(myHandle *obj);
    

    and only in a private header or implementation file, you will put

    struct myHandle
    {
        char val;
    };
    

    The first option is simpler because inside the implementation of frobnicate(), you can access your value simply using *obj while the second option requires to write obj->val. What you gain with the second version is that you force client code to be written correctly.

    In terms of the resulting executable, both versions are equivalent.