加载执行动态库

来源:互联网 发布:sql to_char 用法 编辑:程序博客网 时间:2024/04/30 09:16

void * dlopen(const char* filename, int flag);

打开一个动态库文件,返回一个指针作为句柄handle.失败返回NULL.

flag: RTLD_NOW(RunTime Load Dynamic ):表示立即加载到内存

RTLD_LAZY:表示在使用时才加载.

潜规则:

返回指针的函数一般用正常地址表示成功,NULL表示失败。个别例外返回(void*)0xffffffff表示失败.

char* dlerror(void);取得一个字符串描述动态库操作发生了什么错误。

void * dlsym(void* handle,  const char* symbol);查找指定的符号名在动态库中的地址,失败返回NULL,(严格的做法是在dlsym调用前调用dlerror, dlsym之后再调用dlerror()判断后一次的返回值是否非空来判断是否失败。)

int dlclose(void* handle);关闭动态库,从内存中卸载。

头文件:<dlfcn.h>

这些函数在动态库libdl.so中, gcc -ldl

demo:

#include<stdio.h>

#include<dlfcn.h>

int main()

{

printf("select 1  or 2");

int sel = 0;

scanf("%d", &sel);

void * handle;

if( 1== sel)

{

handle = dlopen("./libch.so", RTLD_NOW);

}else{

handle = dlopen("./liben.so", RTLD_NOW);

}

if( NULL == handle )

{

puts( dlerror() );

return -1;

}

void (*fp)(void);

fp = dlsym(handle, "welcom");

if(NULL == fp )

{

puts( dlerror() );

return -1;

}

fp(); // (*fp)();

dlclose( handle );

}


//


gcc -shared -o libch.so dlzh.c

gcc -shared -o liben.so dlen.c

0 0
原创粉丝点击