天天看點

動态連結庫(一)

一.typedef函數指針用法 

1.簡單的函數指針的應用

形式1:傳回類型(*函數名)(參數表) 

char (*pFun)(int);   

char glFun(int a){ return;}   

void main()   

{   

    pFun = glFun;   

    (*pFun)(2);   

}  

2.使用typedef更直覺更友善

形式1:typedef  傳回類型(*新類型)(參數表)

typedef char (*PTRFUN)(int);   

PTRFUN pFun;   

char glFun(int a){ return;}   

void main()   

{   

    pFun = glFun;   

    (*pFun)(2);   

}

二.檢視動态連結庫資訊

Dependency Walker (depends.exe) 

三.建立動态連結庫

showDlg.h

#include "stdafx.h"
#define EXPORT __declspec(dllexport)//導出函數
extern "C"  EXPORT  void __stdcall  ShowDialog(char* pText);//extern "C" 防止C++編譯器對函數名進行改編
           

ShowDlg.cpp

// ShowDlg.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include "ShowDlg.h"

BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
					 )
{
    return TRUE;
}


void __stdcall ShowDialog(char* pText)
{
	MessageBox(NULL,pText,"提示",0);
}
           

由于_stdcall是一種比較流行的函數調用約定,為了防止發生函數命名改變的情況,可以定義一個.def檔案

ShowDlg.def

LIBRARY ShowDlg.dll//動态連結庫名稱
EXPORTS
ShowDialog = ShowDialog//導出的函數名=動态連結庫内部函數名
           

四.調用動态連結庫

1.動态調用

#include "stdafx.h"
#include "windows.h"
int main()
{
typedef void(__stdcall * funShowInfo)(char* pchData);
//形式1:typedef  傳回類型(*新類型)(參數表)
HMODULE hMod = LoadLibrary("ShowDlg.dll");//加載
if (hMod != NULL)//判斷加載是否成功
{
funShowInfo ShowInfo;//定義函數指針
ShowInfo = (funShowInfo)GetProcAddress(hMod, "ShowDialog");//擷取動态連結庫中的函數
if (ShowInfo)//判斷函數指針是否為空
ShowInfo("皮皮蝦的春天");//調用動态連結庫中的函數
}
FreeLibrary(hMod);//解除安裝動态連結庫
printf("DLL\n");
} 
           

2.靜态調用

需要三個檔案,動态連結庫檔案ShowDlg.dll,動态連結庫頭檔案ShowDlg.h,動态連結庫lib檔案ShowDlg.lib

#include "stdafx.h"
#include "windows.h"
#include "ShowDlg.h"
#pragma  comment(lib,"ShowDlg.lib")
int main()
{
ShowDialog("靜态調用");
printf("DLL\n");
}
           

源碼

http://download.csdn.net/detail/greless/9853300

繼續閱讀