有时候,代码中并不需要提前加载所有的dll,这时候可以选择使用LoadLibrary,GetProcAddress,FreeLibrary这三个函数来加载插件,而对应的插件部分编译成动态库。
适用场景:如各厂商的插件的时候
下面给出例子:
main函数部分,负责获取路径,并通过LoadLibrary加载,然后GetProcAddress获取函数地址,然后FreeLibrary释放动态库
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main(int argc, char** argv)
{
const char* pcExePath = argv[0];
cout << pcExePath << endl;
const char* pcLast = strrchr(pcExePath, '\\');
char szPath[256] = {0};
if(pcLast)
{
memcpy(szPath, pcExePath, pcLast - pcExePath);
cout << szPath << endl;
}
else
{
return -1;
}
string strPath = szPath;
strPath.append("\\hik_plug\\hik_exe_path.dll");
cout << strPath.c_str() << endl;
getchar();
HMODULE a = LoadLibrary(strPath.c_str());
if(!a)
{
cout << GetLastError() << endl;
cout << "Fail to LoadLibrary " << endl;
getchar();
return -2;
}
typedef void (*FARPROC)();
FARPROC test = (FARPROC)GetProcAddress(a,"init");
test();
FreeLibrary(a);
getchar();
return 0;
}
插件部分头文件:
#ifndef __HIK_PLUG_H__
#define __HIK_PLUG_H__
#ifdef __cplusplus
extern "C"{
#endif
__declspec(dllexport) void init();
#ifdef __cplusplus
}
#endif
#endif
插件部分的实际的cpp代码,插件工程编译成dll
#include <WinSock2.h>
#include "hik_plug.h"
#include "HCNetSDK.h"
#include <iostream>
using namespace std;
void init()
{
BOOL bResult = NET_DVR_Init();
if(TRUE == bResult)
{
cout << "Succeed to init" << endl;
}
else
{
cout << "Fail to init" << endl;
}
}
#if 0
int main(int argc, char** argv)
{
init();
return 0;
}
#endif