【Demo 0120】DLLからクラスをエクスポート

3606 ワード

前のセクションでは、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;
  • };

  • .codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif}
    .codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important}
    .linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal}
    .codearea pre.alt{ background-color:#f7f7ff !important}
    .codearea .lnum{color:#4f81bd;line-height:18px}

    Key Code
  • #include
  • #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);
  • }

  • クラスの定義と実装は通常のクラスと変わらないが,クラスの宣言にDLAPIすなわち_を加えただけである.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"), nLeft, nRight, DllClass.Add());
  •     _tprintf(_T("Sub(%d, %d) = %d"), nLeft, nRight, DllClass.Sub());
  •     _tprintf(_T("Min(%d, %d) = %d"), nLeft, nRight, DllClass.Min());
  •     _tprintf(_T("Max(%d, %d) = %d"), nLeft, nRight, DllClass.Max());
  •  
  •     system("pause");
  •     return;
  • }

  • クラスの実現も非常に簡単で、自身のモジュール内のクラスと同様に、DLClassを少し異なる.hがexeにロードされるとDLLAPIは
       _declspec(import)
     
    デモコード