您的位置:首页 > 运维架构 > Linux

C++ windows,linux跨平台动态库加载整理

2014-01-09 21:45 351 查看
windows及linux动态库加载整理:

/*
* Library.h
*
* Created on: Jan 9, 2014
* Author: nohack
*/

#ifndef LIBRARY_H_
#define LIBRARY_H_

#include <stdlib.h>

#ifdef _WIN32_
#include <string>
#endif

#ifdef _GNU_
#include <string.h>
#endif
using namespace std;

class Library {
private:
string _libPath; ///<the path of library
int _libVersion; ///<the version of library

public:
#ifdef _WIN32_
HMODULE _module; ///<the handle of library
#else if _GNU_
void *_module; ///<the handle of library
#endif

public:
Library();
Library(const string filePath, string version="0");
virtual ~Library();
/**
*@brief load library
*/
bool load(string libFilePath);

/**
*@brief get symbol form library
*/
void getSymbol(const string symbolName);

private:
/**
*@brief release library
*/
void releaseLibrary();

};

#endif /* LIBRARY_H_ */


/*
* Library.cpp
*
* Created on: Jan 9, 2014
* Author: nohack
*/

#include "Library.h"
#include <iostream>
#include <sys/stat.h>

#ifdef _GNU_
#include <dlfcn.h>
#include <errno.h>
#include <string.h>
#endif

using namespace std;

bool fileIsExist(string &libFilePath)
{
struct stat statbuf;
return stat(libFilePath.c_str(), &statbuf)== 0;
}

Library::Library()
:_libPath(""),
_libVersion(0),
_module(NULL)
{

}

Library::Library(const string filePath, string version="0")
:_libPath(""),
_libVersion(0),
_module(NULL)
{
if(!load(filePath))
{
std::cout<<"Load library failed !"<<std::endl;
}
}
Library::~Library()
{
releaseLibrary();
}

bool Library::load(string libFilePath)
{
if(_module != NULL)
{
std::cout<<"The library has loaded !"<<std::endl;
return false;
}

if(!fileIsExist( libfilepath ) )
{
std::cout<<"The library is not exist!"<<std::endl;
}
#ifdef _WIN32_
_module = LoadLibrary(libfilepath.data());
if(_module = NULL)
{
std::cout<< GetlastError()<<std::endl;
}
#else if _GNU_
_module = dlopen(libfilepath.c_str(), RTLD_NOW | RTLD_GLOBAL);
if(_module = NULL)
{
std::cout<< strerror(errno)<<std::endl;
}
#endif
return _module != NULL;
}

void Library::getSymbol(const string symbolName)
{
if(_module == NULL)
{
std::cout<<"The library has not loaded !"<<std::endl;
}
#ifdef _WIN32_
return GetProcessAddress(_module, symbolName.c_str());
#else if _GNU_
return dlsym(_module, symbolName.c_str());
#endif
}

void Library::releaseLibrary()
{

if(_module)
{
#ifdef _WIN32_
FreeLibrary(_module);
#else if _GNU_
_module = NULL;
_libPath = ""
#endif
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: