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;
}