VS實現動態庫的創建和使用

 

步驟1:

打開VS2005軟件,創建DLL工程。工程命名test.

  點擊下一步,應用程序類型爲DLL,空工程。

完成,一個新的DLL工程設置完畢,接下來編輯源碼

步驟2:

添加頭文件,命名爲test.h,編輯內容:

#ifndef TEST_H

#define TEST _H //防止重複定義

#endif

#include <stdio.h>   //頭文件引用

 

#if defined DLL_EXPORT  //源文件需引用下一函數

#define DECLDIR __declspec(dllexport)//就是這個

#else

     #define DECLDIR __declspec(dllimport)

#endif

 

#ifdef __cplusplus

extern "C" {

#endif

 

     DECLDIR int add(int a, int b);  //函數聲明

     DECLDIR void function(void);

 

 

 

#endif

解釋:VC中有兩種方式導出DLL文件中的函數

使用 __declspec關鍵字。

創建模板定義文件(Module_Definithion File)即.def文件。

在此使用第一種方法:

_declspec(dllexport)作用是導出函數符號到DLL的一個存儲類中。在頭文件中定義#define DECLDIR __declspec(dllexport)宏來運行這個函數。

使用條件編譯,在源文件中宏定義 #define DLL_EXPORT 來運行這個函數。

//******************************************************************************

步驟3:

創建源文件 test.c

#include <stdio.h>

#define DLL_EXPORT

#include "test.h"

#ifdef __cplusplus

extern "C" {

#endif

     //定義Dll中的所有函數

 

DECLDIR int add(int a, int b)

{

         return a+b;

}

 

DECLDIR void function(void)

{

         printf("DLL called\n");

}

編譯工程,生成test.dll文件和test.lib文件(注:找到工程目錄,這兩個文件在外面的debug文件夾下)。

點擊“生成”即可。

1、  動態庫的調用

使用創建好的DLL庫文件,創建一個控制檯應用程序                                                              

隱式鏈接

 

連接到.lib文件,首先將test.h頭文件,test.dll動態庫文件,test.lib靜態庫文件放在控制檯應用程序工程的目錄中,即源文件所在的文件夾裏。

在使用動態庫時,在C文件的開頭需要加入:

#pragma comment(lib," test.lib")//鏈接.lib文件

//導入需要是要使用的函數,而這些函數則是在創建動態庫時所生命導出的函數

_declspec(dllimport) int add(int a, int b);

 _declspec(dllimport) void function(void);

 

添加源文件test1.cpp,編碼:

#include <stdio.h>

#pragma comment(lib," test.lib")//鏈接.lib文件

_declspec(dllimport) int add(int a, int b);

_declspec(dllimport) void function(void);

int main()

{

function();

     printf(“%d”,add(25,25))

                   return 0;

}

最後顯示結果:

//******************************************************************************

顯式鏈接

只加載.dll文件,但需用到函數指針和Windows 函數,不需要.lib文件和.h頭文件。

#include <stdio.h>

#include <windows.h>

typedef int (*AddFunc)(int, int);

typedef void (*FunctionFunc)(void);//函數指針

int main()

{

     AddFunc _AddFunc;

     FunctionFunc _FunctionFunc;

    //HINSTANCE實例句柄(即一個歷程的入口地址)

    HINSTANCE hInstLibrary = LoadLibraryA("ceshi1.dll");

     //注意,此時的LoadLibraryA()窄字符集和LoadLibraryW()寬字符集的區別,後有介紹。

    if(hInstLibrary == NULL)

     {

         FreeLibrary(hInstLibrary);//釋放DLL獲得的內存,若句柄無效

    }

    //獲得函數的入口地址,還需類型轉換

    _AddFunc = (AddFunc)GetProcAddress(hInstLibrary,"add");

     _FunctionFunc = (FunctionFunc)GetProcAddress(hInstLibrary,"function");

 

     if(_AddFunc==NULL || _FunctionFunc ==NULL)//確定是否成功。

     {

         FreeLibrary(hInstLibrary);

     }

 

     Printf(“%d”,AddFunc(25,25));

     _FunctionFunc();

     FreeLibrary(hInstLibrary);

     return 0;

}

 

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