尽管苹果公司建议将捆绑包扩展
.bundle
很多开发人员给他们
.so
为了跨平台熟悉而扩展。在Linux上,共享模块(MacOS上的包)和共享库(MacOS上的dylib)之间没有区别。
理解这一点,就像
ld
声明,您不能链接到MacOS上的mh_包。它要么需要是一个dylib来链接它,要么需要加载
所以
使用dyld API。
This link
给出了如何在MacOS上动态加载捆绑包的示例:
#include <stdio.h>
#import <mach-o/dyld.h>
int main( )
{
int the_answer;
int rc; // Success or failure result value
NSObjectFileImage img; // Represents the bundle's object file
NSModule handle; // Handle to the loaded bundle
NSSymbol sym; // Represents a symbol in the bundle
int (*get_answer) (void); // Function pointer for get_answer
/* Get an object file for the bundle. */
rc = NSCreateObjectFileImageFromFile("libanswer.bundle", &img);
if (rc != NSObjectFileImageSuccess) {
fprintf(stderr, "Could not load libanswer.bundle.\n");
exit(-1);
}
/* Get a handle for the bundle. */
handle = NSLinkModule(img, "libanswer.bundle", FALSE);
/* Look up the get_answer function. */
sym = NSLookupSymbolInModule(handle, "_get_answer");
if (sym == NULL)
{
fprintf(stderr, "Could not find symbol: _get_answer.\n");
exit(-2);
}
/* Get the address of the function. */
get_answer = NSAddressOfSymbol(sym);
/* Invoke the function and display the answer. */
the_answer = get_answer( );
printf("The answer is... %d\n", the_answer);
fprintf(stderr, "%d??!!\n", the_answer);
return 0;
}