C++ - 动态调用共享库函数

1. 需求.

 

我们需要调用一个函数

 

std::string getValue(int index)

 

这个函数定义在库t1.so里面

 

 

2. t1.so

 

#:cat t1.C

#include <string>

extern "C"
std::string getValue(int index)
{
        switch(index)
        {
        case 1:
                return "111";
        case 2:
                return "222";
        default:
                return "333";
        }
}

 

#: CC -G t1.C -o t1.so

 

3. 用法

 

 

#: cat t2.C

#include <dlfcn.h>
#include <link.h>

#include <string>
#include <iostream>

using namespace std;

std::string (*getValue)(int index);

// 这种定义方式, 和std::string (*func)(int index);是一个意思, C++函数名被mangle成一个字符串, 只要t1.so里面的函数名被声明成getValue, 就可以通过dlsym(...)得到, 然后赋给func变量。

 

 

//

// extern "C" {

// std::string (*getValue)(int index);

// }

 

// 这种模式是不行的, 因为这相当于声明一个外部还是, 而不是定义一个函数, 我们真正需要的是定义一个函数.

// extern "C" std::string (*getValue)(int index);

 

 

int main(int argc, char *argv[])
{
        void *lib = dlopen("t1.so",RTLD_GLOBAL | RTLD_LAZY);
        if (lib==NULL)
        {
                cerr << "Cannot load shared library./n/treason: " << dlerror() << endl;
                return 0;
        }


        if ((getValue=(std::string (*)(int))dlsym(lib, "getValue"))==NULL)
        {
                cerr << "Cannot get symbol./n/treason: " << dlerror() << endl;
                return 0;
        }

        std::string ret = getValue(2);

        cout << ret << endl;
}

 

#: CC t2.C -o t2

 

 

上面程序片在Sun Studio 11编译通过。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值