如何使用objective-C加载dylib或.a(静态库)文件? [英] How to load dylib or .a (static library) file using objective-C?

查看:90
本文介绍了如何使用objective-C加载dylib或.a(静态库)文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 代码:(窗口)

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"链接的情况下获取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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆