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

Linux之共享库封装、使用的典型demo

2015-12-16 20:11 531 查看
## 目录结构

main.cpp

device.h

lib | ev | libdevice.so

| hw | libdevice.so

| kt | libdevice.so

device | device.h evoc_device.cpp hw_device.cpp kt_device.cpp

| hw_lib | hw.c hw.h

## 生成静态库(模拟第三方提供的静态库)

#include "hw.h"

int calcCpuRate()
{
return 90;
}
int calcTemp()
{
return 100;
}


#ifndef HW_H
#define HW_H

int calcCpuRate();
int calcTemp();

#endif


gcc -c hw.c

ar -rc libhw.a hw.o

## 基于静态库生成自己统一接口的共享库

#ifndef DEVICE_H
#define DEVICE_H
#include <string>
using namespace std;

class Device {
public:
Device(){}
virtual int getTemp(){}
virtual int getCpuRate(){}
virtual int getHeight(){}
virtual string getDiskInfo(){}
};

#endif


#include "device.h"
#include <iostream>

class EVoc_Device : public Device {
public:
EVoc_Device():Device(){
cout << "This is Evoc Device...." << endl;
m_temp = 50;
m_cpuRate = 10;
m_height = 20;
m_diskInfo = "well";
}
virtual int getTemp(){
return m_temp;
}
virtual int getCpuRate(){
return m_cpuRate;
}
virtual int getHeight(){
return m_height;
}
virtual string getDiskInfo(){
return m_diskInfo;
}
private:
int m_temp;
int m_cpuRate;
int m_height;
string m_diskInfo;
};

extern "C" Device * create(){
return (new EVoc_Device());
}


TARGET  = libdevice.so
CC      = gcc
CXX     = g++
LDFLAG  = -shared -fPIC

xx:
@echo $(DEV)

ifeq ($(DEV),EVOC)
$(CXX) $(LDFLAG) -o $(TARGET) evoc_device.cpp
endif

ifeq ($(DEV),KONTRON)
$(CXX) $(LDFLAG) -o $(TARGET) kontron_device.cpp
endif

ifeq ($(DEV),HUAWEI)
$(CXX) $(LDFLAG) -o $(TARGET) huawei_device.cpp -I./hw_lib -L./hw_lib -lhw
endif


make DEV=EVOC

生成libdevice.so

## 调度共享库

#include "device.h"
#include <dlfcn.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

using namespace std;
#define DEV_PATH_LEN 20

int main(int argc,char **argv){
char * pDevType = NULL;
if (argc >= 2)
pDevType = argv[1];
else
pDevType = "hw";
char devPath[DEV_PATH_LEN];
memset(devPath ,0,DEV_PATH_LEN);
sprintf(devPath,"./lib/%s/libdevice.so",pDevType);

typedef Device * (*Device_t)();

void * dev_handler = dlopen(devPath ,RTLD_LAZY);
if (!dev_handler){
cout << "Cannot load library: " << dlerror() << '\n';
return 0;
}
dlerror();

Device_t create_method = (Device_t)dlsym(dev_handler,"create");
const char * dlsym_error = dlerror();
if (dlsym_error) {
cerr << "Cannot load symbol create: " << dlsym_error << '\n';
return 1;
}
Device * pDevice = create_method();
if (pDevice){
cout << "Temp:\t" << pDevice->getTemp() << endl;
cout << "Height:\t" << pDevice->getHeight() << endl;
cout << "CpuRate:\t" << pDevice->getCpuRate() << endl;
cout << "DiskInfo:\t" << pDevice->getDiskInfo() << endl;
}
return 0;
}


##

gcc main.cpp -ldevice
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: