linux C++ 共享庫匯出類

bitbit發表於2014-04-20

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"編譯後執行時就會提示:

相關文章