Skip to content

Instantly share code, notes, and snippets.

@isaac-weisberg
Created November 23, 2018 15:24
Show Gist options
  • Select an option

  • Save isaac-weisberg/e02a1d033f567fe36d12dde60f844e63 to your computer and use it in GitHub Desktop.

Select an option

Save isaac-weisberg/e02a1d033f567fe36d12dde60f844e63 to your computer and use it in GitHub Desktop.
Closure mechanism implementation in pure C
#include <stdlib.h>
typedef struct {
int someInt;
char* someString; // and other captured objects
} Captures;
int addingStuff(Captures* captures, int param) {
return captures->someInt + param;
}
typedef struct {
Captures* captures;
int (*lambda)(Captures* captures, int param);
} Closure;
void usage() {
Closure* closure = malloc(sizeof(Closure));
closure->captures = malloc(sizeof(Captures));
closure->captures->someInt = 3;
closure->lambda = addingStuff;
int res = closure->lambda(closure->captures, 35); // 35 + 3 = 38
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment