文件内容:
test.h:
#pragma once
class Test{
public:
Test();
~Test();
void Func(int i);
};
test.cpp:
#include <iostream>
#include "test.h"
using namespace std;
Test::Test(){
cout << __func__ << "()" << endl;
}
Test::~Test(){
cout << __func__ << "()" << endl;
}
void Test::Func(int i){
cout << __func__ << "(" << i << ")" << endl;
}
main.cpp
#include "test.h"
int main(){
Test t;
t.Func(100);
}
3.动态加载库
利用多态性动态加载类
3.1创建
修改test.h:
#pragma once
class ITest{
public:
virtual void Func(int i) = 0;
virtual ~ITest(){}
};
class Test : public ITest{
public:
Test();
~Test();
void Func(int i);
};
extern "C" {
ITest* create(void);
void destroy(ITest *p);
typedef ITest* create_t(void);
typedef void destory_t(ITest*); // 只提供构造函数和析构函数两个接口
}
修改test.cpp:
#include <iostream>
#include "test.h"
using namespace std;
Test::Test(){
cout << __func__ << "()" << endl;
}
Test::~Test(){
cout << __func__ << "()" << endl;
}
void Test::Func(int i){
cout << __func__ << "(" << i << ")" << endl;
}
ITest* create(void){
return new Test;
}
void destroy(ITest *p){
if(NULL != p){
delete p;
}
}
修改main.cpp:
#include <iostream>
#include <cstdlib>
#include <dlfcn.h>
#include "test.h"
using namespace std;
int main(){
void *so_handle = dlopen("./libtest.so", RTLD_LAZY);
if (!so_handle) {
cerr << "Error: load so failed." << endl;
exit(-1);
}
create_t *create = (create_t*) dlsym(so_handle, "create");
char *err = dlerror();
if (NULL != err) {
cerr << err;
exit(-1);
}
ITest *pt = create();
pt->Func(100);
destory_t *destroy = (destory_t*) dlsym(so_handle, "destroy");
err = dlerror();
if (NULL != err) {
cerr << err;
exit(-1);
}
destroy(pt);
pt = NULL;
dlclose(so_handle);
return 0;
}
编译动态加载库:
g++ -shared -fPIC -o libtest.so test.cpp