1、首先我们写个简单的block
typedef void(^Block)();
int globalValue = 1;
int main(int argc, const char * argv[]) {
__block int bn = 2;
int n = 3;
Block b = ^(){
printf("%d %d %d",++bn,++globalValue,n);
};
b();
printf("%d %d",bn, globalValue);
return 0;
}
2、在命令行中使用 clang -rewrite-objc main.m 转成cpp代码,再打开main.cpp找到相关代码
转化后代码如下:
//block声明变成了函数指针申明
typedef void(*Block)();
//全局变量定义没有变
int globalValue = 1;
//__block声明的变量使用个一个结构体来包装,最后一个成员是原来的变量
struct __Block_byref_bn_0 {
void *__isa;
__Block_byref_bn_0 *__forwarding;
int __flags;
int __size;
int bn;
};
//block结构体
struct __main_block_impl_0 {
struct __block_impl impl;
struct __main_block_desc_0* Desc;
int n; //没加__block的外部变量直接定义在结构体内,赋值传参
__Block_byref_bn_0 *bn; // by ref
__main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int _n, __Block_byref_bn_0 *_bn, int flags=0) : n(_n), bn(_bn->__forwarding) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
//block的函数
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
__Block_byref_bn_0 *bn = __cself->bn; // bound by ref
int n = __cself->n; // bound by copy
printf("%d %d %d",++(bn->__forwarding->bn),++globalValue,n);
}
//block的copy函数
static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {_Block_object_assign((void*)&dst->bn, (void*)src->bn, 8/*BLOCK_FIELD_IS_BYREF*/);}
//block的销毁函数
static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->bn, 8/*BLOCK_FIELD_IS_BYREF*/);}
//block的成员结构体,包含一个预留变量,block结构体大小,block copy函数指针,block 销毁函数指针
static struct __main_block_desc_0 {
size_t reserved;
size_t Block_size;
void (*copy)(struct __main_block_impl_0*, struct __main_block_impl_0*);
void (*dispose)(struct __main_block_impl_0*);
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0), __main_block_copy_0, __main_block_dispose_0};
//main方法
int main(int argc, const char * argv[]) {
//带__block的变量用结构体来包装__isa=0,__forwarding=this,flag=0,size=sizeof(__Block_byref_bn_0),bn=2
__attribute__((__blocks__(byref))) __Block_byref_bn_0 bn = {(void*)0,(__Block_byref_bn_0 *)&bn, 0, sizeof(__Block_byref_bn_0), 2};
int n = 3;
//
Block b = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, n, (__Block_byref_bn_0 *)&bn, 570425344));
((void (*)(__block_impl *))((__block_impl *)b)->FuncPtr)((__block_impl *)b);
printf("%d %d",(bn.__forwarding->bn), globalValue);
return 0;
}
结论:
1)block在编译的时候会转换成一个结构体,包含引用的外部非全局变量和block实现
2)全局变量不会被引入block结构体中,普通局部变量直接赋值的方式保存的block结构体中,__block的局部变量会包装在一个结构体内被block引入
3)为什么这里调用bn变量都是使用bn.__forwarding->bn,而不是bn.bn呢,这里先了解下block有3种类型:_NSConcreteGlobalBlock、_NSConcreteStackBlock、_NSConcreteMallocBlock,全局定义的block就是global block,普通定义的block是stack block,但arc下block的赋值会把block拷贝到堆上,变成malloc block,当拷贝的时候,里面的成员也会跟着拷贝,就不再是原来的成员了,__forwarding也会拷贝,值不变,这时候访问bn成员是访问哪个呢,这个时候就由__forwarding来决定,拷贝出的不同block访问的__block变量是同一个