[cpp]
// Service.h, DLL定義(供實現方、調用方使用)
////////////////////////////////////////////////////////////////////////////////
#ifdef SERVICE_EXPORTS
#define SERVICE_API extern "C" __declspec(dllexport)
#else
#define SERVICE_API
//#define SERVICE_API extern "C" __declspec(dllimport)
#endif
interface IService
{
public:
IService() {}
virtual ~IService() {}
public:
virtual void Start() = 0;
virtual void Stop() = 0;
};
typedef IService *(*CreateInstance_t)();
typedef void (*DestroyInstance_t)(IService *pInst);
SERVICE_API IService *CreateInstance();
SERVICE_API void DestroyInstance(IService *pInst);
// Service.cpp, DLL實現
////////////////////////////////////////////////////////////////////////////////
#include "Service.h"
class CService : public IService
{
public:
CService();
virtual ~CService();
public:
virtual void Start();
virtual void Stop();
private:
//.....
};
CService::CService()
{
}
CService::~CService()
{
}
void CService::Start()
{
}
void CService::Stop()
{
}
IService *CreateInstance()
{
return new CService();
}
void DestroyInstance(IService *pInst)
{
if (!pInst) return;
delete pInst;
}
SERVICE_API HRESULT WINAPI DllRegisterServer()
{
//CMD> regsvr32.exe Service.dll 時需要執行的安裝代碼
return S_OK;
}
SERVICE_API HRESULT WINAPI DllUnregisterServer()
{
//CMD> regsvr32.exe /u Service.dll 時需要執行的卸載代碼
return S_OK;
}
// Demo.cpp, DLL調用
////////////////////////////////////////////////////////////////////////////////
#include "Service.h"
int WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
HMODULE hDll = LoadLibraryA("Service.dll");
if (hDll)
{
CreateInstance_t pfnCreateInstance =
(CreateInstance_t)GetProcAddress(hDll, "CreateInstance");
DestroyInstance_t pfnDestroyInstance =
(DestroyInstance_t)GetProcAddress(hDll, "DestroyInstance");
if (pfnCreateInstance && pfnDestroyInstance)
{
IService *pInst = pfnCreateInstance();
if (pInst)
{
pInst->Start();
pInst->Stop();
pfnDestroyInstance(pInst);
}
}
FreeLibrary(hDll);
}
return 0;
}