Linux/unix 提供了使用 dlopen 和 dlsym 方法動態加載庫和調用函數,這套方法在 macOS 和 iOS 上也支持。
dlopen 打開一個庫,獲取句柄。
dlsym 在打開的庫中查找符號的值。
dlclose 關閉句柄。
dlerror 返回一個描述最後一次調用dlopen、dlsym,或 dlclose 的錯誤信息的字符串。
動態調用 printf 函數,編寫測試代碼如下:
#import <dlfcn.h> typedef int (*printf_func_pointer) (const char * __restrict, ...); void dynamic_call_function(){ //動態庫路徑 char *dylib_path = "/usr/lib/libSystem.dylib"; //打開動態庫 void *handle = dlopen(dylib_path, RTLD_GLOBAL | RTLD_NOW); if (handle == NULL) { //打開動態庫出錯 fprintf(stderr, "%s\n", dlerror()); } else { //獲取 printf 地址 printf_func_pointer printf_func = dlsym(handle, "printf"); //地址獲取成功則調用 if (printf_func) { int num = 100; printf_func("Hello exchen.net %d\n", num); printf_func("printf function address 0x%lx\n", printf_func); } dlclose(handle); //關閉句柄 } } int main(int argc, char * argv[]) { @autoreleasepool { dynamic_call_function(); return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }
在手機上運行的輸出結果如下:
Hello exchen.net 100 printf function address 0x189f0da78