Last active
January 10, 2020 15:00
-
-
Save luizdepra/e2ffbd28b64fa9498bda290666906ea0 to your computer and use it in GitHub Desktop.
C Opaque Structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef API_H | |
#define API_H | |
typedef struct { | |
int x; | |
int y; | |
} api; | |
api* create_api(); | |
int get_z(api*); | |
#endif /* API_H */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef INTERNAL_H | |
#define INTERNAL_H | |
#include "api.h" | |
typedef struct { | |
api the_api; | |
int z; | |
} internal; | |
#endif /* INTERNAL_H */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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