c / expert
Snippet
Opaque Handle Pattern for Structural Data Encapsulation
The Opaque Handle pattern hides the internal member declarations of a type from public header interfaces. Callers interact exclusively with pointer handles via factory and accessor functions, ensuring complete encapsulation and stable ABI boundaries in C.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>#include <stdlib.h>typedef struct WidgetImpl* WidgetHandle;struct WidgetImpl {int id;char name[32];};WidgetHandle widget_create(int id) {struct WidgetImpl* w = (struct WidgetImpl*)malloc(sizeof(struct WidgetImpl));if (!w) return NULL;w->id = id;snprintf(w->name, sizeof(w->name), "Widget-%d", id);return w;}void widget_process(WidgetHandle handle) {if (!handle) return;printf("Processing %s (ID: %d)\n", handle->name, handle->id);}void widget_destroy(WidgetHandle handle) {free(handle);}int main(void) {WidgetHandle w = widget_create(101);widget_process(w);widget_destroy(w);return 0;}
Breakdown
1
typedef struct WidgetImpl* WidgetHandle;
Declares an opaque pointer type handle whose concrete struct layout is hidden from public API callers.
2
struct WidgetImpl { int id; char name[32]; };
Defines the internal struct implementation hidden within the implementation module.
3
WidgetHandle widget_create(int id)
Constructs and initializes the encapsulated object, returning an abstract pointer handle.
4
void widget_destroy(WidgetHandle handle)
Deallocates object memory safely through dedicated lifecycle teardown functions.