如何使用Objective-C加载dylib或.a(静态库)文件? [英] How to load dylib or .a (static library) file using objective-C?
问题描述
C#代码:(windows)
C# code : (windows)
Assembly assembly = Assembly.LoadFrom(AssemblyPath);
System.Type[] objTypes = assembly.GetTypes();
Type libType = null;
我想在Mac上实现同样的功能,其中AssemblyPath是静态库(libTEST.a)或dylib的路径文件。在Objective-C(Mac)中可以吗?
我尝试使用NSBundle。但是我想要一些好的解决方案。
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.
推荐答案
首先,这与Xcode 无关
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.
为了加载动态库,请使用 dlopen()
API:
In order to load a dynamic library, use the dlopen()
API:
void *handle = dlopen("/path/to/library.dylib", RTLD_LAZY);
要获取C函数指针:
int (*computeAnswer)(void) = dlsym(handle, "ComputeAnswer");
int answer = computeAnswer(); // 42
要获得不带 extern C
链接(混杂的名称):
To get a C++ function pointer without extern "C"
linkage (mangled name):
int (*mangledFunction)(void) = dlsym(handle, "i$mangledFunction_@v");
您甚至可以通过链接器的Objective-C命名约定来入侵自己编译器:
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);
这篇关于如何使用Objective-C加载dylib或.a(静态库)文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!