為了便於學習,本系列文章轉載於http://www.cppblog.com/suiaiguo/archive/2009/07/20/90619.html,如果需要轉載,請註明轉載原網址。
前面介紹了怎麼從DLL中匯出函數,下面我們來看一下如何從DLL中匯出變數來。
聲明為匯出變數時,同樣有兩種方法:
第一種是用__declspec進行匯出聲明
#ifndef _DLL_SAMPLE_H
#define _DLL_SAMPLE_H
// 如果定義了C++編譯器,那麼聲明為C連結方式
#ifdef __cplusplus
extern "C" {
#endif
// 通過宏來控制是匯入還是匯出
#ifdef _DLL_SAMPLE
#define DLL_SAMPLE_API __declspec(dllexport)
#else
#define DLL_SAMPLE_API __declspec(dllimport)
#endif
// 匯出/匯入變數聲明
DLL_SAMPLE_API extern int DLLData;
#undef DLL_SAMPLE_API
#ifdef __cplusplus
}
#endif
#endif
第二種是用模組定義檔案(.def)進行匯出聲明
LIBRARY DLLSample
DESCRIPTION "my simple DLL"
EXPORTS
DLLData DATA ;DATA表示這是資料(變數)
下面是DLL的實現檔案
#include "stdafx.h"
#define _DLL_SAMPLE
#ifndef _DLL_SAMPLE_H
#include "DLLSample.h"
#endif
#include "stdio.h"
int DLLData;
//APIENTRY聲明DLL函數進入點
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
DLLData = 123; // 在入口函數中對變數進行初始化
break
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
同樣,應用程式調用DLL中的變數也有兩種方法。
第一種是隱式連結:
#include <stdio.h>
#include "DLLSample.h"
#pragma comment(lib,"DLLSample.lib")
int main(int argc, char *argv[])
{
printf("%d ", DLLSample);
return 0;
}
第二種是顯式連結:
#include <iostream>
#include <windows.h>
int main()
{
int my_int;
HINSTANCE hInstLibrary = LoadLibrary("DLLSample.dll");
if (hInstLibrary == NULL)
{
FreeLibrary(hInstLibrary);
}
my_int = *(int*)GetProcAddress(hInstLibrary, "DLLData");
if (dllFunc == NULL)
{
FreeLibrary(hInstLibrary);
}
std::cout<<my_int;
std::cin.get();
FreeLibrary(hInstLibrary);
return(1);
}
通過GetProcAddress取出的函數或者變數都是地址,因此,需要解引用並且轉類型。