How to load dylib or .a (static library) file usin

2020-06-19 09:16发布

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.

2条回答
2楼-- · 2020-06-19 09:34

I would add to what was said earlier, that you need to bridge the class from the dlsym, which returns a C type void*.

So in that case, it will mean doing something of a sort:

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

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

Notice the (__bridge Class) addition there.

For further reference: Pass an Objective-C object to a function as a void * pointer

查看更多
叛逆
3楼-- · 2020-06-19 09:39

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);
查看更多
登录 后发表回答