一、說明
類似Windows系統中的動態連結程式庫,Linux中也有相應的共用庫用以支援代碼的複用。Windows中為*.dll,而Linux中為*.so。下面詳細介紹如何建立、使用Linux的共用庫。
二、建立共用庫
在mytestso.c檔案中,代碼如下:
#include <stdio.h> #include <stdlib.h> int GetMax(int a, int b) { if (a >= b) return a; return b; } int GetInt(char* psztxt) { if (0 == psztxt) return -1;
return atoi(psztxt); }
|
然後使用下列命令進行編譯:
gcc -fpic -shared mytestso.c -o mytestso.so |
-fpic 使輸出的對象模組是按照可重定位地址方式產生的
編譯成功後,目前的目錄下有mytestso.so,此時已成功建立共用庫mytestso.so。
三、使用共用庫
共用庫中的函數可被主程式載入並執行,但是不必編譯時間連結到主程式的目標檔案中。主程式使用共用庫中的函數時,需要事Crowdsourced Security Testing道所包含的函數的名稱字串),然後根據其名稱獲得該函數的起始地址函數指標),然後即可使用該函數指標使用該函數。
在mytest.c檔案中,代碼如下:
#include <dlfcn.h> #include <stdio.h> int main(int argc, char* argv[]) { void* pdlhandle; char* pszerror;
int (*GetMax)(int a, int b); int (*GetInt)(char* psztxt);
int a, b; char* psztxt = "1024";
// open mytestso.so pdlhandle = dlopen("./mytestso.so", RTLD_LAZY); pszerror = dlerror(); if (0 != pszerror) { printf("%s\n", pszerror); exit(1); }
// get GetMax func GetMax = dlsym(pdlhandle, "GetMax"); pszerror = dlerror(); if (0 != pszerror) { printf("%s\n", pszerror); exit(1); }
// get GetInt func GetInt = dlsym(pdlhandle, "GetInt"); pszerror = dlerror(); if (0 != pszerror) { printf("%s\n", pszerror); exit(1); }
// call fun a = 200; b = 600; printf("max=%d\n", GetMax(a, b)); printf("txt=%d\n", GetInt(psztxt));
// close mytestso.so dlclose(pdlhandle); }
|