Monday, April 22, 2013

如何编写DLL实例,很早以前的笔记

在mingw中编写DLL程序
 * 用C++编写DLL程序
用例子来说明
dll.h
#ifndef _DLL_H_  
#define _DLL_H_  
  
#if BUILDING_DLL  
# define DLLIMPORT __declspec (dllexport)  
#else /* Not BUILDING_DLL */  
# define DLLIMPORT __declspec (dllimport)  
#endif /* Not BUILDING_DLL */  


class DLLIMPORT DllClass
{
  public:
    DllClass();
    virtual ~DllClass(void);

    void setValue(int);
    int getValue() const;
  private:  
    int _value;
};  
#endif /* _DLL_H_ */
dllmain.cpp
#include "dll.h"
#include <iostream>
#include <windows.h>

DllClass::DllClass()
{
  std::cout << "Dll class construction" << std::endl;
}


DllClass::~DllClass ()
{
  std::cout << "Dll class destruction" << std::endl;
}

void DllClass::setValue(int n){
  _value=n;
}
int DllClass::getValue() const{
  return _value;
}
BOOL APIENTRY DllMain (HINSTANCE hInst     /* Library instance handle. */ ,
                       DWORD reason        /* Reason this function is being called. */ ,
                       LPVOID reserved     /* Not used. */ )
{
    switch (reason)
    {
      case DLL_PROCESS_ATTACH:
        break;

      case DLL_PROCESS_DETACH:
        break;

      case DLL_THREAD_ATTACH:
        break;

      case DLL_THREAD_DETACH:
        break;
    }

    /* Returns TRUE on success, FALSE on failure */
    return TRUE;
}
调用方法
main.cpp
#include "dll.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
    DllClass dc;
    dc.setValue(100);
    cout << "involved: "<<dc.getValue() << endl;
    return 0;
}
编译DLL源文件
g++.exe -c dllmain.cpp -o dllmain.o -DBUILDING_DLL=1   -g3
连接DLL源文件,并输出描述DLL的def文件和.a文件.
dllwrap.exe --output-def libdlltest.def \
            --driver-name c++ \
            --implib libdlltest.a dllmain.o \
            --no-export-all-symbols \
            --add-stdcall-alias \
            -lgmon \
            -g3 \
            -o dlltest.dll
关于DLL加载的方式有3种.
  1. 隐式, 就象使用静态库一样. 
  2. 显式, 用LoadLibrary/FreeLibrary方法来加载DLL程序. 
  3. 延迟方式, 很类似隐式,但是就并不是在程序开始运行的时候加载DLL.具体还要找更多的文档资料.

No comments:

Post a Comment