【Demo 0120】从DLL中导出类
我们在前几节中学习了如何从DLL中导出函数以及变量,本节中我们学习如何从DLL中导出C++类, 分别演示DLL模块以及EXE模块所实现的代码:
一、DLL模块:
Key Code
- #pragma once
- #ifdef DLLLIB_EXPORTS
- #define DLLAPI _declspec(dllexport)
- #else
- #define DLLAPI _declspec(dllimport)
- #endif
- class DLLAPI CDllClass
- {
- public:
- CDllClass(void);
- ~CDllClass(void);
- void SetData(int nLeft, int nRight);
- int Add();
- int Sub();
- int Min();
- int Max();
- private:
- int m_nLeft;
- int m_nRight;
- };
Key Code
- #include <windows.h>
- #include "DllClass.h"
- CDllClass::CDllClass(void)
- {
- }
- CDllClass::~CDllClass(void)
- {
- }
- void CDllClass::SetData(int nLeft, int nRight)
- {
- m_nLeft = nLeft;
- m_nRight = nRight;
- }
- int CDllClass::Add()
- {
- return (m_nLeft + m_nRight);
- }
- int CDllClass::Sub()
- {
- return (m_nLeft - m_nRight);
- }
- int CDllClass::Min()
- {
- return min(m_nLeft, m_nRight);
- }
- int CDllClass::Max()
- {
- return max(m_nLeft, m_nRight);
- }
类的定义和实现与普通的类没有什么差别,只是在类的声明处加了DLLAPI 即_declspec(dllexport)
二、EXE模块:
Key Code
- #include "./../DllLib/DllClass.h"
- #pragma comment(lib, "./../Debug/DllLib.lib")
- void main()
- {
- int nLeft = 120;
- int nRight = 20;
- CDllClass DllClass;
- DllClass.SetData(nLeft, nRight);
- _tprintf(_T("Add(%d, %d) = %d\n"), nLeft, nRight, DllClass.Add());
- _tprintf(_T("Sub(%d, %d) = %d\n"), nLeft, nRight, DllClass.Sub());
- _tprintf(_T("Min(%d, %d) = %d\n"), nLeft, nRight, DllClass.Min());
- _tprintf(_T("Max(%d, %d) = %d\n"), nLeft, nRight, DllClass.Max());
- system("pause");
- return;
- }
类的实现也非常简单与自身模块内的类一样,稍有些不同的在于将DLLClass.h载入到exe中时DLLAPI将被转换成
_declspec(import)