__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。
__attribute__((cleanup(...))) ,用于修饰一个变量,在它的作用域结束时可以自动执行一个指定的方法,如:

理解:cleanup 方法是这个作用欲结束的时候 也就是说当 notification_applicationDidFinishLaunching 方法的花括号结束的时候才是这个作用域结束,并且是进栈的结构,所以先调用sting的,再执行block的cleanup
所谓作用域结束,包括大括号结束、return、goto、break、exception等各种情况。
当然,可以修饰的变量不止NSString,自定义Class或基本类型都是可以的
假如一个作用域内有若干个cleanup的变量,他们的调用顺序是先入后出的栈式顺序;
而且,cleanup是先于这个对象的dealloc调用的。

- (void)notification_applicationDidFinishLaunching:(NSNotification *)notification
{
__strong NSString *string __attribute__ ((cleanup(stringCleanup))) = @"执行逻辑混淆";
NSLog(@"%@ %@", NSStringFromSelector(_cmd), string);
__strong void (^block) (void) __attribute__ ((cleanup(blockCleanup), unused)) = ^{
NSLog(@"i am a block");
};
}
static void stringCleanup(__strong NSString **string){
NSLog(@"stringCleanup %@", *string);
}
static void blockCleanup(__strong void (^*block)(void)) {
NSLog(@"blockCleanup");
(*block)();
}
__attribute__((always_inline))
如果想要编译器不管在任何时候就强制内联的话,需要在函数申明的时候指定__attribute__((always_inline));
编译器只有在指定-O2的时候,才会将inline函数进行内联展开,如果不指定-O2的时候,还是会给inline函数生成单独的函数段。
//以下汇编代码的作用是替代exit()。
inline __attribute__((always_inline)) void custom_sysexit(void)
{
#ifdef __arm64__
__asm__("mov X0, #1 \t\n"
"mov w16, #1 \t\n" // ip1 指针。
"svc #0x80"
);
#elif __arm__
__asm__(
"mov r0, #1 \t\n"
"mov ip, #1 \t\n"
"svc #0x80"
);
#endif
return;
}
思考:
1、是否可以利用__attribute__设置变量属性来实现类似java中的@Field语法?
例如:@Field("app_stoken") String app_stoken);
2、是否可以利用__attribute__魔法对一些代码执行逻辑进行混淆?
3、是否可以利用__attribute__魔法进行父类的方法和属性进行定义?

更多__attribute__用法参见:
http://www.unixwiz.net/techtips/gnu-c-attributes.html
https://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Type-Attributes.html#Type-Attributes
http://releases.llvm.org/3.8.0/tools/clang/docs/AttributeReference.html
http://clang-analyzer.llvm.org/annotations.html
本文详细介绍了C语言中的__attribute__特性,包括如何使用它来设置函数、变量和类型的属性。特别聚焦于cleanup属性,解释了其在变量作用域结束时自动执行指定清理方法的机制,并探讨了其调用顺序和与dealloc方法的关系。同时,文章还讨论了__attribute__((always_inline))在函数内联中的应用。

2433

被折叠的 条评论
为什么被折叠?



