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;
}