程序中顯示與隱示的調(diào)用 dll
//===================================
//MyAlg.h
//===================================
/*
隱示裝載的dll
從dll中導(dǎo)出一個類,? 使用這個dll中類的可執(zhí)行代碼工程必須和這個dll工程用的是同一編譯器
否則這個dll將不可用
*/
class CMyAlg
{
public:
?__declspec(dllimport) int Add(int a, int b);
};
//===================================
//MyAlg.cpp
//===================================
#include "MyAlg.h"
int CMyAlg::Add(int a, int b)
{
?return (a + b);
}
//===================================
//alg.h
//===================================
/*
顯示裝載的dll
從dll中導(dǎo)出一人函數(shù)和一個變量, 這個不會出現(xiàn)像導(dǎo)出類所碰到的問題, 要以C
風格的型式導(dǎo)出
*/
extern "C" __declspec(dllimport) int Add(int a, int b);
extern "C" __declspec(dllimport) int g_nValue;
//===================================
//test.cpp? 測試前面寫好的dll
//===================================
#include <stdio.h>
#define???EXPLICIT_LOAD
#ifdef EXPLICIT_LOAD?//定義了顯示方法加載DLL
#include <windows.h>
#endif
#ifdef IMPLICIT_LOAD?//定義了隱示方法加載DLL
#include "MyAlg.h"
#include "alg.h"
#pragma comment(lib, "Class.lib")?//dll中導(dǎo)出一個類
#pragma comment(lib, "Win32Dll.lib")//dll中導(dǎo)出一個函數(shù)和變量
#endif
void main(void)
{
#ifdef IMPLICIT_LOAD
//使用隱示方法加載DLL,可以調(diào)用dll中導(dǎo)出的函數(shù)、變量和類
?CMyAlg alg;
?printf("使用隱示方法加載DLL\n");
?printf("CMyAlg::Add(%d, %d) = %d, \n", 1, 2, alg.Add(1, + 2));
?printf("Add(%d, %d) = %d, g_nValue = %d\n\n", 1, 2, Add(1, 2), g_nValue);
#endif
#ifdef EXPLICIT_LOAD?
//使用顯示的方法加載DLL,只能調(diào)用dll中以C風格導(dǎo)出的函數(shù)
?printf("使用顯示的方法加載DLL\n");
?HINSTANCE hIns = LoadLibrary("Win32Dll.dll");
?if(hIns = NULL)
?{
??printf("Load dll failure!\n");
??return;
?}
?
?typedef int(* pAdd)(int, int);
?pAdd pfun = (pAdd)GetProcAddress(hIns, "Add");
?printf("pfun(1, 2) = %d, pfun(1,2)\n");
?FreeLibrary(hIns);
#endif
?getchar();
}
posted on 2006-10-13 08:39 永遇樂 閱讀(2219) 評論(0) 編輯 收藏 引用 所屬分類: Windows MFC