写如下的block声明代码:
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { void (^blockTest)(void) = ^{ NSLog(@"hahha"); }; blockTest(); } return 0; }
经过xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m转成C++后,拿到如下关键代码:
struct __main_block_impl_0 { struct __block_impl impl; struct __main_block_desc_0* Desc; __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int flags=0) { impl.isa = &_NSConcreteStackBlock; impl.Flags = flags; impl.FuncPtr = fp; Desc = desc; } };
struct __block_impl { void *isa; int Flags; int Reserved; void *FuncPtr; };
static void __main_block_func_0(struct __main_block_impl_0 *__cself) { NSLog((NSString *)&__NSConstantStringImpl__var_folders_3q_7klqgj0j63z08zcx0skwjm500000gn_T_main_47560d_mi_0); } static struct __main_block_desc_0 { size_t reserved; size_t Block_size; } __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0)}; int main(int argc, const char * argv[]) { /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; void (*blockTest)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA)); ((void (*)(__block_impl *))((__block_impl *)blockTest)->FuncPtr)((__block_impl *)blockTest); } return 0; }
可将main.m中的代码转为如下代码:
#import <Foundation/Foundation.h> struct __block_impl { void *isa; int Flags; int Reserved; void *FuncPtr; }; struct __main_block_impl_0 { struct __block_impl impl; struct __main_block_desc_0* Desc; }; struct __main_block_desc_0 { size_t reserved; size_t Block_size; }; int main(int argc, const char * argv[]) { @autoreleasepool { void (^block)(void) = ^{ NSLog(@"hahha"); }; struct __main_block_impl_0 *blockStruct = (__bridge struct __main_block_impl_0 *)block; blockStruct->impl.FuncPtr; } return 0; }