Monday, July 23, 2012

Opaque Pointers in C

When designing a library, it is generally considered a good practice to hide the implementation details from the users, i.e encapsulation, this is how it's done in C:
mylib.h
/* The declaration of object_t */
struct object_t;
mylib.c
/* The definition of object_t */
struct object_t {
    int x;
    int y;
    ...
};

/* The compiler will consider object_t an incomplete type,
   so we need to allocate it internally and return a pointer */
struct object_handle_t *new_obj()
{
     return malloc(sizeof(struct object_t));
} 

No comments:

Post a Comment