Created
November 23, 2018 15:24
-
-
Save isaac-weisberg/e02a1d033f567fe36d12dde60f844e63 to your computer and use it in GitHub Desktop.
Closure mechanism implementation in pure 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 <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