c++使用dlopen

该文章展示了一个C++程序如何加载动态链接库(libcaculate.so)并使用dlopen、dlsym函数调用库中定义的add方法。它首先通过CMakeLists.txt构建共享库,然后在main.cpp中使用dlfcn库进行动态加载和调用。
摘要由CSDN通过智能技术生成

相关路径结构

.
├── build
├── caculate.cpp
├── CMakeLists.txt
└── main.cpp

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
add_compile_options(-fPIC)
add_library(caculate SHARED caculate.cpp)

add_executable(main main.cpp)
target_link_libraries(main dl)

caculate.cpp

extern "C"{
    int add(int a,int b)
    {
        return (a + b);
    }

    int sub(int a, int b)
    {
        return (a - b);
    }

    int mul(int a, int b)
    {
        return (a * b);
    }

    int div(int a, int b)
    {
        return (a / b);
    }
}

main.cpp

#include <iostream>
#include <stdlib.h>
#include <dlfcn.h>

typedef int (*CAC_FUNC)(int, int);

int main(){
    void *handle;
    char *error;
    CAC_FUNC cac_func = NULL;

    // open the so file
    handle = dlopen("./libcaculate.so", RTLD_NOW);
    if(!handle){
        std::cout << "dlerror() " << std::endl;
        exit(-1);
    }
    dlerror();

    *(void **) (&cac_func) = dlsym(handle, "add");
    if((error = dlerror()) != NULL){
        std::cout << "error" << std::endl;
        exit(-1);
    }
    std::cout << "add: " << (*cac_func)(2, 7) << std::endl;
    // close the so
    dlclose(handle);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值