OC代码:
1 int main(int argc, const char * argv[]) { 2 3 void (^blk)(void) = ^{ 4 printf("Block\n"); 5 }; 6 7 blk(); 8 9 return 0; 10 }
通过Clang -rewrite-objc命令转成C语言代码:
1 struct __block_impl { 2 void *isa; 3 int Flags; 4 int Reserved; 5 void *FuncPtr; 6 }; 7 8 struct __main_block_impl_0 { 9 struct __block_impl impl; 10 struct __main_block_desc_0* Desc; 11 __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int flags=0) { 12 impl.isa = &_NSConcreteStackBlock; 13 impl.Flags = flags; 14 impl.FuncPtr = fp; 15 Desc = desc; 16 } 17 }; 18 19 static void __main_block_func_0(struct __main_block_impl_0 *__cself) { 20 printf("Block\n"); 21 } 22 23 static struct __main_block_desc_0 { 24 size_t reserved; 25 size_t Block_size; 26 } __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0)}; 27 28 int main(int argc, const char * argv[]) { 29 30 void (*blk)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA)); 31 32 ((void (*)(__block_impl *))((__block_impl *)blk)->FuncPtr)((__block_impl *)blk); 33 34 return 0; 35 }
可以看到整个Block结构如下: