DLL 对C++类的封装

来源:互联网 发布:mac删除文件的快捷键 编辑:程序博客网 时间:2024/06/05 18:48

 

将C++类封装在DLL中,并在DLL中创建静态对象,在外部直接调用相关函数。

 

1, 打开VC2008创建新工程,选择Win32-> Win32 Porject,点击next。

2, 选择Application type:DLL,点击finish

即创建了一个非MFC DLL

 

------------------------------------

因为我们创建的是非MFC的DLL,所以需要定义一些宏,表示导出:

1,新建TestWin32DLL.h 

   在TestWin32DLL.h 中定义

 

#ifdef UQ_EXPORTS

#define UGBASE_API __declspec(dllexport)

#else

#define UQBASE_API __declspec(dllimport)

#endif

 

2,在TestWin32DLL.cpp中包含TestWin32DLL.h

3,在预定义中添加UQ_EXPORTS项

 

-------------------------------------

 

接下来,创建导出类(CItest),主要供外部使用:

.h文件

#pragma once

 

#ifndef _ITEST_H

#define _ITEST_H

 

#include "TestWin32DLL.h"

 

namespace UQ

{

 

    class UQBASE_CLASS CItest

    {

    public:

        CItest(void);   // 必要时可以把构造函数定义为私有,限制在外面定义对象

        ~CItest(void);

 

    public:

        static CItest& GetInstance();

        int Add(int nX, int nY);

    };

 

};

 

#endif

 

.cpp文件

 

#include "StdAfx.h"

#include "Itest.h"

 

namespace UQ

{

 

CItest::CItest(void)

{

}

 

CItest::~CItest(void)

{

}

 

CItest& CItest::GetInstance()

{

    static CItest _test;

 

    return _test;

}

 

int CItest::Add(int nX, int nY)

{

    return nX + nY;

}

 

};

 

 

这样一个简单的DLL就完成了。下面看如何调用。

 

因为我们在DLL中创建了自身的静态对象,用GetInstance()返回,所以我们采用隐式调用DLL比较方便,在exe编译时将DLL也一同编译。

需要使用DLL的时候调用:CItest::GetInstance().Add(x, y); 即可调用。

 

1,在工程中添加TestWin32DLL.lib (并将TestWin32DLL.lib 文件拷贝的编译环境下)

2,在调用文件添加头文件:#include "../TestWin32DLL/Itest.h"

3,添加命名空间:using namespace UQ;

4,调用: int n = CItest::GetInstance().Add(10, 20);  即可以这样的方式使用。

 

 

接着昨天的写.

 

还有一种封装方式,就是类只在DLL中可见,那么外部Load这个DLL的之后,取得函数CreateExeCore的指针,并执行该函数,那么产生的对象实体是CExeCore,返回的类型是IEXEcore (IEXEcore 是纯虚函数)。外部调用的时候看到永远是EXEcore  中声明的纯虚函数而已。这样子,接口更简单,调用的时候只需要执行一个函数之后就不用再频繁的获取函数的指针。大大的简化的操作的简单性,也便于并行开发。

 

namespace UQ

{

 

    class IEXEcore

    {

    public:

        virtual void Init() = 0;

        virtual void Destory() = 0;

    };

 

    class IDevice

    {

    public:

        virtual void Init() = 0;

    };

 

    extern "C"

    {

        UQBASE_API IEXEcore* CreateExeCore();

    }

 

};

 

 

 

namespace UQ

{

 

IEXEcore* CreateExeCore()

{

    IEXEcore * pCore = NULL;

 

    try

    {

        pCore = new CExeCore;

    }

    catch (...)

    {

        return NULL;

    }

 

    return pCore;

}

 

 

};

 

 

 

 

 

 

 

原创粉丝点击