linux下的共享库是一项让人激动的技术,可以利用它充分提高系统的扩展能力,如插件式设计,个人认为它比windows的动态链接库功能更强大。以下是我在开发共享库经过一番折磨总结的需要注意的几点,仅做自勉。
共享库的对外接口函数的声明必须加上extern “C”。 使用共享库对话接口函数生成的对象指针时在该对象未被释放之前不能关闭共享库句柄,否则会出现segmentation fault错误。以下是一个插件式设计的示例
主执行程序:main.cpp
#include
#include
#include "SMSGamePlugin.h"
int main(int argc, char** argv)
{
void *GameLib = dlopen("./Flower.so", RTLD_LAZY);
const char *dlError = dlerror();
if (dlError)
{
std::cout << "dlopen error!" << dlError << std::endl;
return(-1);
}
CSMSGamePlugin *(*pGetGameObject)(void);
pGetGameObject = (CSMSGamePlugin *(*)(void))dlsym(GameLib, "GetGameObject");
dlError = dlerror();
if (dlError)
{
std::cout << "dlsym error!" << dlError << std::endl;
return(-1);
}
CSMSGamePlugin *pGame = (*pGetGameObject)();
pGame->Initialize();
pGame->Load();
pGame->Handle();
delete *pGame;
dlclose(GameLib);
}
公用基类部分:SMSGamePlugin.h
#ifndef __SMSGamePlugin_h__
#define __SMSGamePlugin_h
class CSMSGamePlugin
{
public:
virtual int Initialize(void) = 0;
virtual int Load(void) = 0;
virtual int Handle(void) = 0;
};
#endif
编译:g++ -rdynamic -ldl -s -o Test main.cpp
共享库部分:
共享库头文件:Flower.h
#ifndef __Flower_h__
#define __Flower_h__
#include "SMSGamePlugin.h"
extern "C" CSMSGamePlugin *GetGameObject(void);
class CFlower: public CSMSGamePlugin
{
public:
virtual int Initialize(void);
virtual int Load(void);
virtual int Handle(void);
};
#endif
共享库实现文件:Flower.cpp
#include
#include "Flower.h"
CSMSGamePlugin *GetGameObject(void)
{
return(new CFlower());
}
int CFlower::Initialize(void)
{
std::cout << "Initialize()" << std::endl;
return(0);
}
int CFlower::Load(void)
{
std::cout << "Load()" << std::endl;
return(0);
}
int CFlower::Handle(void)
{
std::cout << "Handle()" << std::endl;
return(0);
}
编译:
g++ -c Flower.cpp
g++ -shared -o Flower.so
注意:
如果不加extern "C"编译后运行时就会提示:
dlsym error!./Test: undefined symbol: GetGameObject
本文地址:http://com.8s8s.com/it/it27591.htm