linux下載入動態連結程式庫的方法:以下以觸控螢幕為例:介紹是如何載入一下共用庫的。
首先讓我們看看以下幾個函數:
dlopen()
功能:開啟一個動態連結程式庫
包含標頭檔:
#include <dlfcn.h>
函數定義:
void * dlopen( const char * pathname, int mode );
函數描述:
在dlopen的()函數以指定模式開啟指定的動態串連庫檔案,並返回一個控制代碼給調用進程。使用dlclose()來卸載開啟的庫。
dlclose(handle);
功能:關閉一個動態連結程式庫
dlsym()
函數原型: void* dlsym(void* handle,const char* symbol)
該函數在<dlfcn.h>檔案中。
handle是由dlopen開啟動態連結程式庫後返回的指標,symbol就是要求擷取的函數的名稱,函數傳回值是void*,指向函數的地址,供調用使用
getenv()
功 能: 從環境中取字串,擷取環境變數的值
標頭檔: stdlib.h
用 法:char *getenv(char *envvar);
函數說明:getenv()用來取得參數enwar環境變數的內容。參數enwar為環境變數的名稱,如果該變數存在則會返回指向該內容的指標。環境變數的格式為enwar=value
傳回值: 執行成功則返回指向該內容的指標,找不到符合的環境變數名稱則返回NULL
alloca()
包含在標頭檔malloc.h中. 在某些系統中會宏定義成_alloca使用.
int load_module(struct tsdev *ts, const char *module, const char *params, int raw)
{
struct tslib_module_info * (*init)(struct tsdev *, const char *);
struct tslib_module_info *info;
char fn[1024];
void *handle;
int ret;
char *plugin_directory=NULL;
if( (plugin_directory = getenv("TSLIB_PLUGINDIR")) != NULL ) {
//fn = alloca(sizeof(plugin_directory) + strlen(module) + 4);
strcpy(fn,plugin_directory);
} else {
//fn = alloca(sizeof(PLUGIN_DIR) + strlen(module) + 4);
strcpy(fn, PLUGIN_DIR);
}
/*構造共用庫路徑*/
strcat(fn, "/");
strcat(fn, module);
strcat(fn, ".so");
#ifdef DEBUG
printf ("Loading module %s\n", fn);
#endif
handle = dlopen(fn, RTLD_NOW);
if (!handle)
return -1;
init = dlsym(handle, "mod_init");
if (!init) {
dlclose(handle);
return -1;
}
info = init(ts, params);
if (!info) {
dlclose(handle);
return -1;
}
info->handle = handle;
if (raw) {
ret = __ts_attach_raw(ts, info);
} else {
ret = __ts_attach(ts, info);
}
if (ret) {
info->ops->fini(info);
dlclose(handle);
}
return ret;
}