VC++ 動態庫有2種加載方式,其中顯式加載較爲常見。
c++一般把動態庫封裝成類的樣子,對外提供一個接口,在類中實現功能。通常一個動態庫可以有幾個接口不等。下面是簡單代碼實現
===================
接口類
#ifndef _TASK_INTERFACE_H_
#define _TASK_INTERFACE_H_
//動態鏈接庫接口類
class Task{
public :
Task(){}
virtual ~Task(){}
virtual void DoTask()=0;//任務接口
};
#endif
=================
任務實現類
#ifndef _WRITELOG_H_
#define _WRITELOG_H_
#include "BaseTaskInterface.h"
#include <iostream>
class WriteLog: public Task
{
public :
WriteLog();
virtual ~WriteLog();
virtual void DoTask();//導出類自然是想用類的成員函數。注意:導出類要用的成員函數必須聲明成虛函數。如果不想研究爲什麼,請務必記住!
bool init();
void over();
private:
FILE * fp;
}
;
extern "C"
{
_declspec(dllexport) Task* createlog();//對外接口。返回一個類
};
typedef WriteLog*(*CreateWriteLog)();//函數指針
#endif
--------------------------cpp---------------------
#include "WriteLog.h"
WriteLog::WriteLog()
{
}
WriteLog::~WriteLog(){}
bool WriteLog::init()
{
fp=fopen("Task.log","wb+");
if(fp)return true;
return false;
}
void WriteLog::over()
{
fclose(fp);
}
void WriteLog::DoTask()//工作函數
{
if(init())
{
fwrite("日誌開始記錄",13,1,fp);
over();
}
else
over();
}
Task* createlog() //對外接口函數返回一個寫日誌類
{
return new WriteLog();
}
===========================================動態庫加載代碼=======================
#include <iostream>
#include <windows.h>
#include "./../../WorkFactroy/WorkFactroy/WriteLog.h"
using namespace std;
void loaddll(char* funcname,char* strdll=NULL,char* strexportfunc=NULL)
{
//暫時先不實現輸出參數的形式
HINSTANCE hdll=LoadLibrary(L"WorkFactroy");
if(hdll!=NULL)
{
printf("動態庫 WorkFactroy.dll加載成功\n ");
}
CreateWriteLog creater=(CreateWriteLog)GetProcAddress(hdll,funcname);
if(!creater)
{
printf("dll加載失敗\n");
FreeLibrary(hdll);
}
else
{
WriteLog* p=creater();
p->DoTask();
FreeLibrary(hdll);
}
}
int main()
{
loaddll("createlog");
return 0;
}