• C++动态链接库实践


    参考:https://www.cnblogs.com/Anker/p/3746802.html

    gcc -fPIC -shared calc.c -o libcalc.so, 编译得到

     在linux上 man dlopen可以得到以下信息:

    头文件注释:

    实践内容:

    #include <stdio.h>
    #include <stdlib.h>
    #include <dlfcn.h>
    
    //动态链接库路径
    #define LIB_CACULATE_PATH "/home/dahui/work/workspace/CStudy/src/libcalc.so"
    
    //函数指针
    typedef int (*CAC_FUNC)(int, int);
    
    int main(void) {
    
        printf("!!!Hello World!!!
    "); /* prints !!!Hello World!!! */
    
        void *handle;
        char *error;
        CAC_FUNC cac_func = NULL;
    
        //打开动态链接库
        handle = dlopen(LIB_CACULATE_PATH, RTLD_LAZY);
        if (!handle) {
            fprintf(stderr, "%s
    ", dlerror());
            exit(EXIT_FAILURE);
        }
    
        //清除之前存在的错误
        dlerror();
    
        //获取一个函数
        *(void **) (&cac_func) = dlsym(handle, "add");
        //cac_func = (CAC_FUNC) dlsym(handle, "add");
        if ((error = dlerror()) != NULL) {
            fprintf(stderr, "%s
    ", error);
            exit(EXIT_FAILURE);
        }
        printf("add: %d
    ", (*cac_func)(2, 7));
    
        cac_func = (CAC_FUNC) dlsym(handle, "sub");
        printf("sub: %d
    ", cac_func(9, 2));
    
        cac_func = (CAC_FUNC) dlsym(handle, "mul");
        printf("mul: %d
    ", cac_func(3, 2));
    
        cac_func = (CAC_FUNC) dlsym(handle, "div");
        printf("div: %d
    ", cac_func(8, 2));
    
        printf("!!!Hello World!!!"); /* prints !!!Hello World!!! */
    
        //关闭动态链接库
        dlclose(handle);
        //exit(EXIT_SUCCESS);
    
        printf("!!!Hello World!!!"); /* prints !!!Hello World!!! */
    
        return EXIT_SUCCESS;
    }

    输出:

  • 相关阅读:
    Gym 101194L / UVALive 7908
    POJ 2259
    POJ 2559
    Gym 101194E / UVALive 7901
    Gym 101194D / UVALive 7900
    一种整数集上二分的正确写法
    日常训练记录
    Gym 101194C / UVALive 7899
    Gym 101194A / UVALive 7897
    HDU 5542
  • 原文地址:https://www.cnblogs.com/do-your-best/p/11437836.html
Copyright © 2020-2023  润新知