Skip to content

Instantly share code, notes, and snippets.

@kristate
Last active December 22, 2017 23:57
Show Gist options
  • Save kristate/4699204 to your computer and use it in GitHub Desktop.
Save kristate/4699204 to your computer and use it in GitHub Desktop.
A note on how to work with ARC, Objective-C blocks and C libraries. (久利寿でも分かりにくかったので共有いたします!)
//A note on how to work with ARC, Objective-C blocks and C libraries.
//with love from kristopher on a Sunday (2013.2.3@5:46a JST)
//License: Public-Domain
//あるLibraryのAsync Callback TypeDef
typedef void (somelibrary_doasync_cb)(int state, uintptr_t user_data);
//あるLibraryのAsync Function
void somelibrary_doasync(somelibrary_doasync_cb callback, uintptr_t user_data);
//われわれのBlockDef
typedef void (^StatusHandlerBlock)(int state);
//われわれのCallback:
void my_callback(int state, uintptr_t user_data);
//To C land (Cの世界へ)
- (void) doSomethingAsyncWithBlock: (StatusHandlerBlock)response_block {
//Blocks are actually NSObjects, so we have to copy and __bridge_retained the pointer
(void)somelibrary_doasync(my_callback, (uintptr_t)(__bridge_retained CFTypeRef)([response_block copy]) );
}
//From C land (Cの世界から)
void my_callback(int state, uintptr_t user_data) {
//...
__block StatusHandlerBlock block_handler = (__bridge_transfer StatusHandlerBlock)(CFTypeRef)user_data;
block_handler(state);
block_handler = nil; //ARCだからpsudo-release when done.
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment