文章目錄
- 1.建立輸出定義標頭檔
- 2.實現標頭檔提供的介面
- 3.配置先行編譯宏(Preprocessor Definitions)
- 4.配置輸出lib檔案
之前寫過一篇關於Windows Mobile和Wince(Windows Embedded CE)下封裝Native DLL的文章,原文如下:
Windows Mobile和Wince(Windows Embedded CE)下如何封裝Native DLL提供給.NET Compact Framework進行調用
原文主要針對如何封裝的Native DLL提供給.NET Compact Framework的程式來調用。但是如果按照原文的方法進行封裝,使用Native C++調用該封裝DLL會有一些麻煩,需要動態載入該DLL,關於動態載入,我之前也寫過一篇文章,原文如下:
如何在Windows Mobile下使用Native C++動態載入DLL
動態載入有其好處,但是如果封裝的DLL和調用方都是內部的程式,使用初始化時候載入(也叫做靜態載入),在開發時會更加方便和簡單。下面講述如何封裝DLL為調用方提供靜態載入服務。
1.建立輸出定義標頭檔
// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the MY32FEETWIDCOMM_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// MY32FEETWIDCOMM_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifdef MY32FEETWIDCOMM_EXPORTS
#define MY32FEETWIDCOMM_API __declspec(dllexport)
#else
#define MY32FEETWIDCOMM_API __declspec(dllimport)
#endif
// This class is exported from the 32feetWidcommWM.dll
class MY32FEETWIDCOMMWM_API CMy32feetWidcommWM {
public:
CMy32feetWidcommWM(void);
// TODO: add your methods here.
};
extern MY32FEETWIDCOMMWM_API int nMy32feetWidcommWM;
MY32FEETWIDCOMMWM_API int fnMy32feetWidcommWM(void);
調用方需要#include該標頭檔。
2.實現標頭檔提供的介面
// 32feetWidcommWM.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "32feetWidcommWM.h"
#include <windows.h>
#include <commctrl.h>
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// This is an example of an exported variable
MY32FEETWIDCOMMWM_API int nMy32feetWidcommWM=0;
// This is an example of an exported function.
MY32FEETWIDCOMMWM_API int fnMy32feetWidcommWM(void)
{
return 42;
}
// This is the constructor of a class that has been exported.
// see 32feetWidcommWM.h for the class definition
CMy32feetWidcommWM::CMy32feetWidcommWM()
{
return;
}
3.配置先行編譯宏(Preprocessor Definitions)
封裝DLL的項目會輸出介面 __declspec(dllexport) ,而調用方會輸入介面 __declspec(dllimport) ,見標頭檔定義。
4.配置輸出lib檔案
調用方需要連結該lib檔案。
完成了。