Created
June 30, 2011 19:50
-
-
Save jido/1057053 to your computer and use it in GitHub Desktop.
Using closure and continuation-passing style in C
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 struct | |
| { | |
| char* description; | |
| } event; | |
| typedef void (*fun)(); | |
| typedef struct | |
| { | |
| fun invoke; | |
| } closure; | |
| typedef struct { closure proto; int n; } mymainclosure; | |
| void mymain(closure* self, closure* creturn, closure* cthrow) | |
| { | |
| if (self->invoke != mymain) | |
| { | |
| event exc = {.description = "Badly formed closure in mymain"}; | |
| cthrow->invoke(cthrow, exc); | |
| } | |
| else | |
| { | |
| int n = ((mymainclosure*) self)->n; | |
| creturn->invoke(creturn, n+1); | |
| } | |
| } | |
| int main(int n, char** args) | |
| { | |
| mymainclosure m = {.proto = {.invoke = mymain}, .n = 6}; | |
| void myreturn(closure* self, int n) | |
| { | |
| printf("Returned %d\n", n); | |
| } | |
| void mythrow(closure* self, event exc) | |
| { | |
| printf("Threw event: %s\n", exc.description); | |
| } | |
| m.proto.invoke(&m, &(closure){.invoke = myreturn}, &(closure){.invoke = mythrow}); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment