linux C++ 共享库导出类

1.共享库的对外接口函数的声明必须加上extern “C”。

2.使用共享库对话接口函数生成的对象指针时在该对象未被释放之前不能关闭共享库句柄,否则会出现segmentation fault错误。

以下是一个插件式设计的示例:

1、主执行程序: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)

{

< "dlopen error!" << dlError <<

return(-1);

}

CSMSGamePlugin *(*pGetGameObject)(void);

pGetGameObject = (CSMSGamePlugin *(*)(void))dlsym(GameLib, "GetGameObject");

dlError = dlerror();

if (dlError)

{

< "dlsym error!" << dlError <<

return(-1);

}

CSMSGamePlugin *pGame = (*pGetGameObject)();

pGame->Initialize();

pGame->Load();

pGame->Handle();

delete *pGame;

dlclose(GameLib);

}

2、公用基类部分: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

3、共享库部分:

共享库头文件: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

4、共享库实现文件:Flower.cpp

#include

#include "Flower.h"

CSMSGamePlugin *GetGameObject(void)

{

return(new CFlower());

}

int CFlower::Initialize(void)

{

< "Initialize()" <<

return(0);

}

int CFlower::Load(void)

{

< "Load()" <<

return(0);

}

int CFlower::Handle(void)

{

< "Handle()" <<

return(0);

}

编译:

g++ -c Flower.cpp

g++ -shared -o Flower.so

5、注意:

如果不加extern "C"编译后运行时就会提示:

上一篇:express不是内部或外部命令


下一篇:JavaScript深入浅出第1课:箭头函数中的this究竟是什么鬼?