Skip to content

Instantly share code, notes, and snippets.

@jido
Created June 30, 2011 19:50
Show Gist options
  • Select an option

  • Save jido/1057053 to your computer and use it in GitHub Desktop.

Select an option

Save jido/1057053 to your computer and use it in GitHub Desktop.
Using closure and continuation-passing style in C
#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