Skip to content

Instantly share code, notes, and snippets.

@luizdepra
Last active January 10, 2020 15:00
Show Gist options
  • Save luizdepra/e2ffbd28b64fa9498bda290666906ea0 to your computer and use it in GitHub Desktop.
Save luizdepra/e2ffbd28b64fa9498bda290666906ea0 to your computer and use it in GitHub Desktop.
C Opaque Structure
#include <stdlib.h>
#include "api.h"
#include "internal.h"
api* create_api() {
internal* in = malloc(sizeof(internal));
in->the_api.x = 1;
in->the_api.y = 2;
in->z = 3;
return &in->the_api;
}
int get_z(api* the_api) {
internal* in = (internal*)the_api;
return in->z;
}
#ifndef API_H
#define API_H
typedef struct {
int x;
int y;
} api;
api* create_api();
int get_z(api*);
#endif /* API_H */
#ifndef INTERNAL_H
#define INTERNAL_H
#include "api.h"
typedef struct {
api the_api;
int z;
} internal;
#endif /* INTERNAL_H */
#include <stdio.h>
#include "api.h"
int main(int argc, char **argv) {
api* the_api = create_api();
printf("x = %d\n", the_api->x);
printf("y = %d\n", the_api->y);
// There is no z in api
//printf("z = %d\n", the_api->z);
printf("z = %d\n", get_z(the_api));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment