The Opaque Pointer Pattern
You can have something similar than C++ objects in C, you can:
Define a struct with your state data
Define functions which take a pointer to the structure as the first parameter.
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.
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