Dll的創建與使用

 一. 創建Dll

1. 使用__declspec(dllexport)導出函數或類。

    Note:確認LOGUTILCPP_API已經定義。Property Pages->Configuration Properties->C/C++->Preprocessor->Preprocessor Definitions.

#ifdef

LOGUTILCPP_EXPORTS

#define

LOGUTILCPP_API extern "C" __declspec(dllexport)

#else

#define LOGUTILCPP_API extern "C" __declspec(dllimport)

#endif

 

// This function is exported from the LogUtilCPP.dll

LOGUTILCPP_API

void PrintLog();

 

// This class is exported from the LogUtilCPP.dll

class

LOGUTILCPP_API CLogUtilCPP {

public

:    

        static CLogUtilCPP* GetInstance();

        void LogBegin(wstring LogfileName);

        void LogError(wstring strFormat,...);

        void LogInfo(wstring strFormat,...);

        void LogWarning(wstring strFormat,...);

        void LogEnd();

}

 

2. 使用def文件導出函數。

    創建一個普通的.h文件和.CPP文件,.h文件如下:

#include

<windows.h>

// TODO: add your methods here.

void

LogBegin(LPCWSTR LogfileName);

void

LogError(LPCWSTR strFormat,...);

void

LogInfo(LPCWSTR strFormat,...);

void

LogWarning(LPCWSTR strFormat,...);

void

LogEnd();

 

   def文件格式如下:

LIBRARY "LogUtilCPP"

DESCRIPTION "LogUtilCPP.Dll [Get .bmp picture if it is failed]"

EXPORTS

LogBegin        @1

LogError          @2

LogInfo           @3

LogWarning   @4

LogEnd            @5

 

3. 使用def文件導出類

    參照上一篇文章,"用DEF文件從Dll中導出C++類"。http://blog.csdn.net/nathannemo/archive/2008/12/15/3521205.aspx

 

4. 關於DllMain函數

   使用VS嚮導創建一個Dll工程會自動產生一個DllMain函數,如果你沒有更新(即沒有使用)這個DllMain函數,可以將它刪除掉。

   當Windows加載DLL模塊時調用這一函數。系統首先調用全局對象的構造函數,然後調用全局函數DLLMain。如果程序員沒有爲DLL模塊編寫一個DLLMain函數,系統會從其它運行庫中引入一個不做任何操作的缺省DLLMain函數版本。在單個線程啓動和終止時,DLLMain函數也被調用。

 

二. Dll的使用

方法一步驟:

1. Reference Dll工程。

2. 包含Dll的頭文件。

3. 像普通的成員函數一樣使用。

 

方法二步驟:

1.將Dll的頭文件,.lib文件,.dll文件拷到當前工程文件夾中。

2.包含Dll的頭文件。

3.Property Pages->Configuration Properties->Linker->Input->Additional Dependencies 添加.lib文件。

4.像普通函數一樣使用。

 

方法三步驟:

1.將.Dll文件拷到當前工程文件夾中。

2.使用動態調用的方式使用,實例如下:

typedef

void (* PrintfLogWarning)(LPCWSTR,...);

HINSTANCE hinstLib = LoadLibrary(L

"LogUtillCPP.Dll");

if

(hinstLib)

{

      PrintfLogWarning pLogWarning = (PrintfLogWarning)GetProcAddress (hinstLib,

"LogWarning");

      pLogWarning(L

"Log Warning.");

}

FreeLibrary(hinstLib);

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章