c / expert
Snippet
Encapsulation with Opaque Pointers (ADTs)
Opaque pointers (often called 'handles' or the PIMPL idiom) allow for complete data encapsulation in C. By only providing a forward declaration in the header and defining the structure in the source file, clients cannot access internal fields directly. This improves binary compatibility (ABI) because the structure's layout can change without requiring clients to recompile.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
// In header (public interface)typedef struct connection_s* connection_t;connection_t conn_create(const char *url);void conn_send(connection_t c, const char *msg);// In source (implementation details hidden)struct connection_s {int socket_fd;char buffer[1024];bool is_encrypted;};
Breakdown
1
typedef struct connection_s* connection_t;
Declares a pointer to an incomplete type, hiding its structure from the user.
2
struct connection_s {
Definition inside the .c file; only visible to the implementation functions.
3
connection_t conn_create(...);
Public API returns the handle, but the user doesn't know the size of the underlying struct.