关于Windows下做动态插件,需要用到的LoadLibrary的代码

有时候,代码中并不需要提前加载所有的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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值