【C++ 动态库加载和使用】
/*
** File name: Library.h
** Author:
** Date: 2024-10-31
** Brief: 动态库加载类
** Copyright (C) 1392019713@qq.com All rights reserved.
*/
#ifndef LIBRARY_H
#define LIBRARY_H
#include <string>
#include <iostream>
#include "SystemExportLib.h"
#ifdef _WIN32
#include <windows.h>
typedef HMODULE Handle;
#elif __linux__
#include <dlfcn.h>
typedef void* Handle;
#endif //
class SYSTEM_EXPORT CLibrary
{
public:
CLibrary();
virtual ~CLibrary();
bool OpenLibrary(std::string const& strfilePath);
void* Solve(std::string const &strName);
CLibrary& operator=(CLibrary const &rParamter) = delete;
CLibrary(CLibrary const &rParamter) = delete;
private:
void CloseLibrary();
private:
Handle m_handle;
};
#endif // !
#include "../Include/Library.h"
CLibrary::CLibrary()
{
m_handle = nullptr;
}
CLibrary::~CLibrary()
{
CloseLibrary();
}
#ifdef _WIN32
bool CLibrary::OpenLibrary(std::string const& strfilePath)
{
std::wstring wfilePath(strfilePath.begin(), strfilePath.end());
m_handle = ::LoadLibrary(wfilePath.c_str());
if (!m_handle)
{
std::cerr << "Failed to open library: " << GetLastError() << std::endl;
return false;
}
return true;
}
void* CLibrary::Solve(std::string const& strFuncName)
{
if (!m_handle)
{
return nullptr;
}
return ::GetProcAddress(m_handle, strFuncName.c_str());
}
void CLibrary::CloseLibrary()
{
if (!m_handle)
{
return;
}
::FreeLibrary(m_handle);
m_handle = nullptr;
}
#elif __linux__
bool CLibrary::OpenLibrary(std::string const& strfilePath)
{
m_handle = dlopen(strfilePath.c_str(), RTLD_LAZY);
if(!m_handle)
{
std::cerr << "Failed to open library: " << dlerror() << std::endl;
return false;
}
return true;
}
void* CLibrary::Solve(std::string const& strName)
{
if (!m_handle)
{
return nullptr;
}
return dlsym(m_handle, strName.c_str());
}
void CLibrary::CloseLibrary()
{
if(!m_handle)
{
return;
}
dlclose(m_handle);
m_handle = nullptr;
}
#endif
使用
std::string libraryName = "PI_GCS2_DLL.dll";
std::string libraryPath = std::filesystem::current_path().string() + "\\" + libraryName;
m_bOpen = m_Library.OpenLibrary(libraryName);
PI_ConnectRS232 = (PFPI_ConnectRS232)m_Library.Solve("PI_ConnectRS232");
PI_MOV = (PFPI_MOV)m_Library.Solve("PI_MOV");
m_nId = PI_ConnectRS232(1, 115200);
原文地址:https://blog.csdn.net/weixin_45397344/article/details/143613389
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!