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编译通过。