编程技术记录

世界你好!

1、attribute DATA 宏

#define ZL_PULGIN_DATA(sectname) __attribute((used, section("__DATA,"#sectname" ")))
#define ZL_PULGIN(key,value) \
    const char * k##key##_##value##_zl ZL_PULGIN_DATA(ZLABCEDFG) = ""#key":"#value"";

//ZLABCEDFG 可以自由定义,但不能超过8个字符

2、在实现文件如.m中使用

ZL_PULGIN(hello,world)

3、在运行时读取

读取函数

#include <mach-o/getsect.h>
#include <mach-o/loader.h>
#include <mach-o/dyld.h>
#include <dlfcn.h>
#import <objc/runtime.h>
#import <objc/message.h>

static NSArray<NSString *>* BHReadConfiguration(const char *section)
{
    NSMutableArray *configs = [NSMutableArray array];

    Dl_info info;
    dladdr(BHReadConfiguration, &info);

#ifndef __LP64__
    //        const struct mach_header *mhp = _dyld_get_image_header(0); // both works as below line
    const struct mach_header *mhp = (struct mach_header*)info.dli_fbase;
    unsigned long size = 0;
    uint32_t *memory = (uint32_t*)getsectiondata(mhp, "__DATA", section, & size);
#else /* defined(__LP64__) */
    const struct mach_header_64 *mhp = (struct mach_header_64*)info.dli_fbase;
    unsigned long size = 0;
    uint64_t *memory = (uint64_t*)getsectiondata(mhp, "__DATA", section, & size);
#endif /* defined(__LP64__) */

    for(int idx = 0; idx < size/sizeof(void*); ++idx){
        char *string = (char*)memory[idx];

        NSString *str = [NSString stringWithUTF8String:string];
        if(!str)continue;

        if(str) [configs addObject:str];
    }

    return configs;

}

执行结果

NSArray *ret = BHReadConfiguration("ZLABCEDFG");

//ret 应为  ["hello:world"]

其一个应用场景就是iOS的组件注册。

发表回复

© Beli. All Rights Reserved.