• 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"编译后运行时就会提示:

  • 相关阅读:
    matlab中size函数总结
    sudo apt-get install ubuntu-desktop, Error: unable to locate package
    java打包打包
    java2exe exe4j crack
    java程序换图标
    jQuery学习——CSS
    jQuery学习——属性
    jQuery学习——表单
    jQuery学习——内容筛选&可见性筛选
    jQuery学习——基本筛选
  • 原文地址:https://www.cnblogs.com/skyofbitbit/p/3676491.html
Copyright © 2020-2023  润新知