dopen变函数变参数实现

论坛 期权论坛 脚本     
匿名网站用户   2020-12-21 07:49   30   0

dopen打开库,
调用变函数,传入变参数

g++ lib_call.c -o lib_call -ldl

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <string>
#include <vector>
#include <stdarg.h>

typedef  std::string (*p_callApp)(const std::vector<std::string>& args);

#define callApp(...)   _callApp(__VA_ARGS__, NULL)


#define LIB_DIR         "/usr/lib/libjs.so"

//let to compiling warning
//std::string _callApp(char * fmt, ...) {
std::string _callApp(const char * fmt, ...) {
    void *handle;
    char *error;
    p_callApp p;
    std::string ret_val = "error";

    va_list ap;
    int i = 0;
    char *str;
    std::vector<std::string> args;


    if(fmt) {
        printf("callApp is %s\n", fmt);
    } else {
        printf("func is null\n");
        return ret_val;
    }

    va_start(ap, fmt);
    do {
        str = va_arg(ap, char*);    
        if(str) {
            printf("%d->%s\n", i++, str);
            args.push_back(str);
        }   
    } while(str);
    va_end(ap);


    handle = dlopen(LIB_DIR, RTLD_LAZY);
    //handle = dlopen(LIB_DIR, RTLD_NOW);
    if(!handle) {
        printf("dlopen %s fail:%s\n", LIB_DIR, dlerror());
        return ret_val;
    } else {
        printf("dlopen %s ok here~~\n", LIB_DIR);
    }   
    //p = (p_callApp)dlsym(handle, "Set_DHCP_Enabled");
    p = (p_callApp)dlsym(handle, fmt);
    if((error = dlerror()) != NULL) {
        printf("%s fail %d %s\n", __FUNCTION__, __LINE__, error);
        return ret_val;
    } else {
        printf("get func ok\n");
    }
    ret_val = (*p)(args);
    //    printf("result:%s\n", ret_val.data());
    dlclose(handle);

    return ret_val;
}

int main(void)
{
    std::string ret_val;

    //ret_val = callApp(NULL);
    ret_val = callApp("Is_DHCP_or_Static", "eth0");
    printf("result:%s\n", ret_val.data());
    ret_val = callApp("Get_Hardware_Info");
    printf("result:%s\n", ret_val.data());
    //ret_val = _callApp("Set_DHCP_Enabled", "true", "eth0", NULL);
    ret_val = callApp("Set_DHCP_Enabled", "true", "eth0");
    printf("result:%s\n", ret_val.data());

    return 0;
}

dlopen潜在问题

https://blog.csdn.net/xqhrs232/article/details/51305421

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP