我创建了一个名为libmathClass.so的测试库,将从下面的代码中加载它。这个共享对象有一个类和库调用被创建来返回这个类的对象。
我如何从下面的主要代码中调用这个对象的方法。由于链接器不知道方法的定义,所以我会从ld(链接器)中得到未定义的引用错误。
void* handle;
handle=dlopen("math1/libmathClass.so", RTLD_LAZY);
if(!handle)
{
cout<<"error loading library: "<<dlerror()<<endl;
exit(2);
}
else
{
cout<<"***libmathClass.so library load successful!"<<endl;
}
void* (*mathInit) ();
mathInit = (void* (*)())dlsym(handle, "CreateMathOperationInstance");
if(!mathInit)
{
cout<<"error loading instance method: "<<dlerror()<<endl;
exit(3);
}
else
{
cout<<"***method load successful!"<<endl;
}
mathOperationClass *mathInstance;
auto obj = (*mathInit)();
if(!obj)
{
cout<<"object is not created"<<endl;
exit(4);
}
else
{
cout<<"object created!!!"<<endl;
mathInstance = reinterpret_cast<mathOperationClass *>(obj);
}
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
cout<< mathInstance->AddInt(num1, num2)<<endl;
我使用的编译命令是 - g++ --std=c++11 -g -o dynamicTest dynamicMain.cpp -ldl
错误信息: dynamicMain.cpp:54: 对 `mathOperationClass::AddInt(int, int)' 的引用未定义 collect2: 错误:ld 返回 1
mathInstance
的对象,以使用AddInt()
方法。 - adrtamCreateMathOperationInstance
导出为extern "C"
?如果没有,你需要提供名称的重载版本(不建议这样做)。 - Galik