The Opaque Pointer Pattern

You can have something similar than C++ objects in C, you can:

  1. Define a struct with your state data

  2. Define functions which take a pointer to the structure as the first parameter.

  3. Declare a variable with that struct type to create an instance of the “Object”.


Object Life Cycle

When using the Opaque Pointer Pattern, declare *_create and *_destroy functions.

*_create work like a constructor in C++, which perform allocation and initialization of an instance and return the opaque pointer.

*_destroy work like a destructor in C++, which clean up the instance, making it NULL-and-VOID for future use.

typedef struct ringbuffer_instance_t * ringbuffer_t;

In many embedded systems, dynamic memory allocation is strongly discouraged. The use of statically allocated memory is preferred. However, Dynamic Memory is OK if only allocated at system startup and not during normal operations.

Opaque Pointer are good if you need multiple instances, or general-purpose libraries.


Summary

In summary, the Opaque Pointer Pattern is a way to create objects in C similar to C++ objects. It involves defining a struct with state data, functions that take a pointer to the struct as the first parameter, and declaring a variable with the struct type to create an instance of the object. The pattern also includes the use of create and destroy functions to handle the object's lifecycle. The Opaque Pointer Pattern is particularly beneficial when multiple instances are needed or when creating general-purpose libraries. Dynamic memory allocation is discouraged, and statically allocated memory is preferred.

Last updated