Last active
November 11, 2018 03:38
-
-
Save isaac-weisberg/20fae7497f2a37486450f6a9a1f4a47c 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
| struct FooReturn { | |
| int (^getBaz)(void); | |
| void (^setBaz)(int newValue); | |
| }; | |
| struct FooReturn foo(int initialBazValue) { | |
| __block int baz = initialBazValue; | |
| int (^getBaz)(void) = ^{ | |
| return baz; | |
| }; | |
| void (^setBaz)(int newValue) = ^(int newValue){ | |
| baz = newValue; | |
| }; | |
| // In both of these blocks, identifier `baz` refers | |
| // to THE SAME object (location in memory). | |
| // Since `baz` is of `__block` storage type, | |
| // it's dynamically allocated | |
| // somewhere not in the `foo`'s stack frame. | |
| /* Pre-C99 | |
| struct FooReturn res; | |
| res.getBaz = getBaz; | |
| res.setBaz = setBaz; | |
| */ | |
| // This shit requires C99+ though | |
| return (struct FooReturn){ | |
| getBaz, | |
| setBaz | |
| }; | |
| } | |
| void bar() { | |
| struct FooReturn fooObj = foo(3); | |
| int currValue = fooObj.getBaz(); // 3 | |
| fooObj.setBaz(5); | |
| int newValue = fooObj.getBaz(); // 5 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment