Skip to content

Instantly share code, notes, and snippets.

@isaac-weisberg
Last active November 11, 2018 03:38
Show Gist options
  • Select an option

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

Select an option

Save isaac-weisberg/20fae7497f2a37486450f6a9a1f4a47c to your computer and use it in GitHub Desktop.
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