dopen变函数变参数实现

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值