我想从linux上的C++库中调用一个函数。我有一个图书馆的共享对象。我想调用从ydmg库返回int的方法getAge()。
以下是我所写的代码:
testydmg.cpp
#include "ydmg/bd.h"
#include "yut/hash.h"
#include "dlfcn.h"
extern "C" int getAge();
class testydmg{
public:
testydmg::testydmg(const yutHash& user){
}
testydmg::testydmg(){
}
testydmg::~testydmg(){
}
int testydmg::getFunction(){
void *handle;
int (*voidfnc)();
handle = dlopen("ydmg.so",RTLD_LAZY);
if(handle == NULL){
printf("error in opening ydmg lib");
} else {
voidfnc = (int (*)())dlsym(handle, "getAge");
(*voidfnc)();
printf("class loaded");
}
ydmgBd obj;
obj.getAge();
printf("Inside getFunction()...");
dlclose(handle);
}
};我编译并链接代码,如下所示:
gcc -fPIC -shared -l stdc++ -i/home/y/linux 64/gcc 1.6.0/include-i/home/y/libexec64 64/gcc 1.6.0/include/linux -I/home/y/include testydmg.cpp -o libTestYdmg.so libydmg.so
然后在新的共享对象(即libTestYdmg.so )中检查方法
nm,-C,libTestYdmg.so,egrep,getAge,我通过运行上面的命令一无所获。
这是否意味着它没有从库中获得getAge()方法。你能纠正一下我哪里出错了吗?
发布于 2011-10-31 07:04:15
您希望使用ydmgDB::getAge(),但您正在向库请求getAge()。这是不正确的,只需创建一个ydmgDB对象并调用它的方法getAge(),而不加载与编译命令行链接的库。
你不需要dlopen库。
此外,getAge并没有真正包含在libTestYdmg.so中。您必须使用以下方法在libydmg.so中查找它:
nm -C libydmg.so | grep getAge发布于 2011-10-31 07:58:03
如果您对在C++代码中实际使用dlopen感兴趣,请查看C++ dlopen迷你指南,其中包括示例代码和一些可能重要的警告。
https://stackoverflow.com/questions/7950570
复制相似问题