Question

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.

Was it helpful?

Solution

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);

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top