如何从依赖包中重新导出 dylib 符号

Dan*_*nra 4 xcode linker dylib

使用 Xcode,我希望从 mach-o 捆绑包二进制文件中重新导出符号(具体来说是一个函数),该符号最初是在 dylib 中定义的。

我已经尝试过 -sub_library 链接器开关,但这似乎没有重新导出 dylib 符号,可能是因为我自己没有构建 dylib(?)

Xcode 的链接器似乎不支持 reexport-l / reexport_library 开关。

有任何想法吗?

小智 5

如果我理解正确的话,这可能就是您正在寻找的。我将使用 libpthread 作为假设的 dylib,其中包含您想要重新导出的函数。

mybundle.c

#include <pthread.h>
#include <stdio.h>
void *foo(void *ctx) {
    puts((char *)ctx);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

mybundle.exp

_foo
_pthread_create
_pthread_join
Run Code Online (Sandbox Code Playgroud)

编译包,动态链接到 libpthread.dylib:

josh$ gcc -bundle -lpthread -Wl,-exported_symbols_list,mybundle.exp -o mybundle.so mybundle.c
Run Code Online (Sandbox Code Playgroud)

myloader.c

#include <dlfcn.h>
#include <pthread.h>    // merely for type definitions
#include <assert.h>
#include <stdio.h>

int main() {
    void *(*foo)(void *ctx);
    /* the following cannot be declared globally without changing their names, 
       as they are already (and unnecessarily) declared in <pthread.h> */
    int (*pthread_create)(pthread_t *thrd, const pthread_attr_t *attr, void *(*proc)(void *), void *arg);
    int (*pthread_join)(pthread_t thrd, void **val);

    void *bundle;
    assert(bundle = dlopen("mybundle.so", RTLD_NOW));
    assert(foo = dlsym(bundle, "foo"));
    assert(pthread_create = dlsym(bundle, "pthread_create"));
    assert(pthread_join = dlsym(bundle, "pthread_join"));

    pthread_t myThrd;
    pthread_create(&myThrd, 0, foo, "in another thread");
    pthread_join(myThrd, 0);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译加载器:

josh$ gcc myloader.c -o myloader
Run Code Online (Sandbox Code Playgroud)

跑步:

josh$ ./myloader
in another thread
Run Code Online (Sandbox Code Playgroud)

请注意,myloader 完全没有链接到 pthread,但 pthread 函数是通过捆绑包在运行时加载并可用的。