【Demo 0120】从DLL中导出类

我们在前几节中学习了如何从DLL中导出函数以及变量,本节中我们学习如何从DLL中导出C++类, 分别演示DLL模块以及EXE模块所实现的代码:

一、DLL模块:

Key Code
  1. #pragma once
  2. #ifdef DLLLIB_EXPORTS
  3.     #define DLLAPI  _declspec(dllexport)
  4. #else
  5.     #define DLLAPI  _declspec(dllimport)
  6. #endif
  7.  
  8. class DLLAPI CDllClass
  9. {
  10. public:
  11.     CDllClass(void);
  12.     ~CDllClass(void);
  13.     void SetData(int nLeft, int nRight);
  14.     int  Add();
  15.     int  Sub();
  16.     int  Min();
  17.     int  Max();
  18. private:
  19.     int m_nLeft;
  20.     int m_nRight;
  21. };

Key Code
  1. #include <windows.h>
  2. #include "DllClass.h"
  3.  
  4.  
  5. CDllClass::CDllClass(void)
  6. {
  7.  
  8. }
  9.  
  10. CDllClass::~CDllClass(void)
  11. {
  12. }
  13.  
  14. void CDllClass::SetData(int nLeft, int nRight)
  15. {
  16.     m_nLeft = nLeft;
  17.     m_nRight = nRight;
  18. }
  19.  
  20. int CDllClass::Add()
  21. {
  22.     return (m_nLeft + m_nRight);
  23. }
  24. int CDllClass::Sub()
  25. {
  26.     return (m_nLeft - m_nRight);
  27. }
  28.  
  29. int CDllClass::Min()
  30. {
  31.     return min(m_nLeft, m_nRight);
  32. }
  33.  
  34. int CDllClass::Max()
  35. {
  36.     return max(m_nLeft, m_nRight);
  37. }

     类的定义和实现与普通的类没有什么差别,只是在类的声明处加了DLLAPI 即_declspec(dllexport)

二、EXE模块:

Key Code
  1. #include "./../DllLib/DllClass.h"
  2. #pragma comment(lib, "./../Debug/DllLib.lib")
  3.  
  4. void main()
  5. {
  6.     int nLeft = 120;
  7.     int nRight = 20;
  8.  
  9.     CDllClass DllClass;
  10.     DllClass.SetData(nLeft, nRight);
  11.     _tprintf(_T("Add(%d, %d) = %d\n"), nLeft, nRight, DllClass.Add());
  12.     _tprintf(_T("Sub(%d, %d) = %d\n"), nLeft, nRight, DllClass.Sub());
  13.     _tprintf(_T("Min(%d, %d) = %d\n"), nLeft, nRight, DllClass.Min());
  14.     _tprintf(_T("Max(%d, %d) = %d\n"), nLeft, nRight, DllClass.Max());
  15.  
  16.     system("pause");
  17.     return;
  18. }

    类的实现也非常简单与自身模块内的类一样,稍有些不同的在于将DLLClass.h载入到exe中时DLLAPI将被转换成

   _declspec(import)

演示代码

原文地址:https://www.cnblogs.com/ztercel/p/2648150.html