How to load dylib or .a (static library) file using objective-C?

天涯浪子 提交于 2019-12-05 03:18:11

问题


C# code : (windows)

Assembly assembly = Assembly.LoadFrom(AssemblyPath);
System.Type[] objTypes = assembly.GetTypes();
Type libType = null;

I want to achieve same for Mac where AssemblyPath is path of static library (libTEST.a) or dylib file. Is it possible in Objective-C (Mac)? I tried with NSBundle. But i want some good solution.


回答1:


First off, this has precisely nothing to do with Xcode.

Now, you can't load static libraries dynamically, because a static library is just a collection of object files, which are not, by themselves, executable.

In order to load a dynamic library, use the dlopen() API:

void *handle = dlopen("/path/to/library.dylib", RTLD_LAZY);

To get a C function pointer:

int (*computeAnswer)(void) = dlsym(handle, "ComputeAnswer");
int answer = computeAnswer(); // 42

To get a C++ function pointer without extern "C" linkage (mangled name):

int (*mangledFunction)(void) = dlsym(handle, "i$mangledFunction_@v");

You can even hack yourself through the Objective-C naming convention of the linker compiler:

@class MyShinyClass;
Class cls = dlsym(handle, "OBJC_CLASS_$_MyShinyClass");

MyShinyClass *instance = [[cls alloc] init];

When you're done with the library, dispose of it:

dlclose(handle);


来源:https://stackoverflow.com/questions/21375475/how-to-load-dylib-or-a-static-library-file-using-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!