so 庫加載 __attribute__((constructor))


動態庫生成: 

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


動態加載:

#include <dlfcn.h>


       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 <stdio.h>
#include <string.h>
#include <dlfcn.h>

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 <stdio.h>
#include <string.h>

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


發佈了63 篇原創文章 · 獲贊 11 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章