通过dlopen使用动态库

动态库制作

dlopen 动态加载Frameworks

使用dlopen和dlsym方法动态加载库和调用函数

动态库使用

链接器:符号是怎么绑定到地址上的

问题:在APP运行时通过dlopendlsym链接加载bundle里面的动态库

dlopen:以指定模式打开指定的动态链接库文件,并返回一个句柄给调用进程。

void * dlopen( const char * pathname, int mode ); 
mode:(可多选的)
// 表示动态库中的symbol什么时候被加载
RTLD_LAZY 暂缓决定,等有需要的时候再解析符号
RTLD_NOW 立即决定,返回前解除所有未决定的符号
// 表示symbol的可见性
RTLD_GLOBLE 允许导出符号
RTLD_LOCAL

使用系统framework

NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"];
void *lib = dlopen("/System/Library/Frameworks/AVFoundation.framework/AVFoundation", RTLD_LAZY);
if (lib) {
    Class playerClass = NSClassFromString(@"AVAudioPlayer");
    SEL selector = NSSelectorFromString(@"initWithData:error:");
     _runtime_Player = [[playerClass alloc] performSelector:selector withObject:[NSData dataWithContentsOfFile:resourcePath] withObject:nil];
    selector = NSSelectorFromString(@"play");
    [_runtime_Player performSelector:selector];
    NSLog(@"动态加载播放");
    dlclose(lib);
}

使用第三方动态库

使用动态库有两种方式,一种是将动态库添加未依赖库,这样会在工程启动时加载动态库,一种是使用dlopen在运行时加载动态库,这两种方式的区别在于加载动态库的时机。

在iOS上如果使用了方式二,是不能上架到App Store的。

1、将动态库的头文件添加到项目中

2、编译工程文件。生成APP的包文件,在项目Products文件夹下

3、将framework添加到APP的包文件(鼠标右键显示包内容)中

这样基本就可以运行成功了

// 1.获取动态库路径
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"MangoSDK" ofType:nil];
// 2.打开动态库
void *lib = dlopen([resourcePath UTF8String], RTLD_LAZY);
if (lib == NULL) {
    // 打开动态库出错
    fprintf(stderr, "%s", dlerror());
    exit(EXIT_FAILURE);
} else {
    // 获取类
    Class util = NSClassFromString(@"MGUtils");
    // 获取方法
    SEL selector = NSSelectorFromString(@"getMessage");
    id obj = [[util alloc] init];
    // 执行
    NSString *message = [obj performSelector:selector];
    dlclose(lib);
    return message;
}
return nil;

你可能感兴趣的:(通过dlopen使用动态库)