C++动态载入动态库【AIX】

部分内容转自[http://www.360doc.com/content/10/1213/22/4947005_77867631.shtml]
函数说明:
1.  打开动态链接库:
    #include <dlfcn.h>
    void *dlopen(const char *filename, int flag);
    该函数返回操作句柄,如:
    void *pHandle = dlopen(strSoFilePath, RTLD_LAZY);
flag:
   RTLD_LAZY: 暂缓决定,等有需要时再解出符号  
   RTLD_NOW :立即决定,返回前解出所有未决定的符号。  
   RTLD_LOCAL :默认的,如果既没有标志指定 。在这个库中定义的符号不是可用来解决在随  后加载的 库的引用。
   RTLD_GLOBAL :允许导出符号,这个库中定义的符号将用于随后加载的库符号解析。

2.  取动态对象地址:
    #include <dlfcn.h>
    void *dlsym(void *pHandle, char *symbol);
    dlsym根据动态链接库操作句柄(pHandle)与符号(symbol),返回符号对应的地址。
    使用这个函数不但可以获取函数地址,也可以获取变量地址。比如,假设在so中
    定义了一个void mytest()函数,那在使用so时先声明一个函数指针:
    void (*pMytest)(),然后使用dlsym函数将函数指针pMytest指向mytest函数,
    pMytest = (void (*)())dlsym(pHandle, "mytest");

3.  关闭动态链接库:
    #include <dlfcn.h>
    int dlclose(void *handle);
    该函数将该.so的引用计数减一,当引用计数为0时,将它从系统中卸载。

4.  动态库错误函数:
    #include <dlfcn.h>
    const char *dlerror(void);
    当动态链接库操作函数执行失败时,dlerror可以返回出错信息,返回值为NULL时
    表示没有错误信息。

示例:
1.动态库代码 myFunc.cpp

#include <stdio.h>

extern "C"
int myAdd(int a, int b)
{
    printf("func called.\n");

    return a+b;
}
xlc编译命令:

xlc -q64 -o libmyFunc.o -c myFunc.cpp

xlc -q64 -qmkshrobj -o libmyFunc.so libmyFunc.o

2.源程序代码 myTest.cpp

#include <stdio.h>
#include <dlfcn.h>

int main()
{
    printf("main begin.\n");
    
    void *handle;
    int (*myAdd)(int, int);
    char *error;


    handle = dlopen ("./libmyFunc.so", RTLD_LAZY);

    if (!handle) 
    {
        printf ("dlopen fail :%s\n", dlerror());

        return 1;
    }


    myAdd = (int (*)(int, int))dlsym(handle, "myAdd");

    if ((error = dlerror()) != NULL) 
    {
        printf ("dlsym fail :%s\n", error);

        return 1;
    }

    int temp = myAdd(3,4);
    
    printf("temp = [%d]\n", temp);

    dlclose(handle);

    return 0;

}

xlc编译命令:

xlc -q64 -brtl -o myTest myTest.cpp

3.执行
./myTest

4.输出
main begin.
func called.
temp = [7]

总结:

1.动态库名最好为libxxx.so
2.动态库中函数需要声明为extern "C"
3.编译主应用程序时需要加-brtl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值