linux下載入動態連結程式庫的方法

來源:互聯網
上載者:User

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;
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.