Last active
August 29, 2015 13:57
-
-
Save fowlmouth/9442788 to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
typedef void (*cleanup_function) (void*); | |
// the interface | |
struct IPoint { | |
float *x, *y; | |
cleanup_function cleanup; | |
}; | |
void ipoint_print (struct IPoint ip) { | |
printf("x: %f, y: %f\n", *ip.x, *ip.y); | |
} | |
void ipoint_cleanup (struct IPoint *ip){ | |
if (ip->cleanup) | |
((void (*)(struct IPoint *))(ip->cleanup))(ip); | |
} | |
void cleanup_ipoint (struct IPoint *ip) { free(ip->x); free(ip->y); } | |
typedef struct { float x, y; } Point; | |
// use point as IPoint | |
struct IPoint point_ipoint (Point *p) { | |
struct IPoint result; | |
result.x = &p->x; | |
result.y = &p->y; | |
result.cleanup = 0; | |
return result; | |
} | |
typedef struct{ float left,top,w,h; } Rect; | |
// use rect as IPoint | |
struct IPoint rect_ipoint (Rect *r) { | |
float *x = (float*)malloc(sizeof(float)); | |
*x = r->left + (r->w / 2); | |
float *y = (float*)malloc(sizeof(float)); | |
*y = r->top + (r->h / 2); | |
struct IPoint result; | |
result.x = x; | |
result.y = y; | |
result.cleanup = (cleanup_function)(&cleanup_ipoint); | |
return result; | |
} | |
int main(void) { | |
Point p = {10,20}; | |
struct IPoint ip = point_ipoint(&p); | |
ipoint_print(ip); | |
ipoint_cleanup(&ip); | |
Rect r = {0,0,50,100}; | |
ip = rect_ipoint(&r); | |
ipoint_print(ip); | |
ipoint_cleanup(&ip); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment