c++学习笔记十六(动态链接库与静态链接库--类篇)

本文是C++学习笔记的一部分,主要探讨动态链接库和静态链接库在类使用上的实践。文章详细介绍了如何创建动态加载库,并通过修改头文件(test.h)、源文件(test.cpp)以及主程序(main.cpp)来实现动态加载类的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件内容:
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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值