设为首页 加入收藏

TOP

so 库加载 __attribute__((constructor))
2014-11-24 00:58:13 来源: 作者: 【 】 浏览:3
Tags:加载 __attribute__ constructor

动态库生成:


gcc -Wall -shared -fPIC -o libss.so libss.c // 库名和源文件自定义


动态加载


#include


void *dlopen(const char *filename, int flag); // filename 动态库名(如libss.so),flag为 RTLD_NOW 或 RTLD_LAZY,RTLD_NOW 库中的所有函数在dlopen返回前都加载,


// RTLD_LAZY 库中的函数在用时才加载


char *dlerror(void); // dlopen dlsym dlclose的执行若有错误,返回描述错误的字符串


void *dlsym(void *handle, const char *symbol); //返回函数指针


int dlclose(void *handle); // 卸载库


Link with -ldl.


例:


udlopen.c


#include
#include
#include


int main(int argc, char **argv)
{
void (*print)();
int (*add)(int, int);
void *handle;

if (argc < 2)
return -1;

handle = dlopen(argv[1], RTLD_LAZY);
if (!handle) {
printf("dlopen failed: %s\n", dlerror());
return -1;
}

print = dlsym(handle, "print");
if (!print) {
printf("dlsym failed: %s\n", dlerror());
return -1;
}
print();

add = dlsym(handle, "add");
if (!add) {
printf("dlsym failed: %s\n", dlerror());
return -1;
}
add(1, 2);

dlclose(handle);

return 0;
}


libss.c


#include
#include


void print()
{
printf("I am print\n");
}


int add(int a, int b)
{
printf("Sum %d and %d is %d\n", a, b, a + b);
return 0;
}
//static void king() __attribute__((constructor(101))); the following is also right
static __attribute__((constructor(101))) void king()
{
printf("I am king\n");
}


编译执行
gcc -Wall -shared -fPIC -o libss.so libss.c -ldl
gcc -Wall -o udlopen udlopen.c

./udlopen libss.so

I am king
I am print
Sum 1 and 2 is 3


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Lua 编程问题 下一篇LRU缓存算法 - C++版

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: