因專案需要多程序共享資源訪問....
#include #include #include typedef struct titem;
typedef structtbank;
typedef struct tbankctrl;
static titem g_titem = ,
, ,, ,
};static tbank g_tbank = , };
static tbankctrl g_bankctrl;
extern "c"
tbankctrl *getbankctrl()
int add(int a,int b)
int sub(int a, int b)
int mul(int a, int b)
int div1(int a, int b)
}
交叉編譯
2. 主原始碼編譯編譯
#include #include #include //動態鏈結庫路徑
#define lib_caculate_path "./libdync.so"
typedef struct titem;
typedef structtbank;
typedef struct tbankctrl;
//函式指標
typedef int (*cac_func)(int, int);
typedef tbank * (*cac_func_bank)();
typedef tbankctrl * (*cac_func_bank_ctrl)();
int main(int argc, char *ar**)
//清除之前存在的錯誤
dlerror();
//獲取乙個函式
*(void **) (&cac_func) = dlsym(handle, "add");
if ((error = dlerror()) != null)
printf("add: %d\n", (*cac_func)(2,7));
cac_func = (cac_func)dlsym(handle, "sub");
printf("sub: %d\n", cac_func(9,2));
cac_func = (cac_func)dlsym(handle, "mul");
printf("mul: %d\n", cac_func(3,2));
cac_func = (cac_func)dlsym(handle, "div1");
printf("div: %d\n", cac_func(8,2));
#if 0
cac_func_bank = (cac_func_bank)dlsym(handle, "getbank");
ptbank = cac_func_bank();
for (ibankidx = 0; ibankidx < 2; ibankidx++) }
//關閉動態鏈結庫
//dlclose(handle);
exit(exit_success);
}
交叉編譯
add was used.
add: 9
sub was used.
sub: 7
mul was used.
mul: 6
div1 was used.
div: 4
bankname: bank-a, item: item-a, id=1
bankname: bank-a, item: item-b, id=2
bankname: bank-a, item: item-c, id=3
bankname: bank-a, item: item-d, id=4
bankname: bank-a, item: item-e, id=5
bankname: bank-b, item: item-a, id=1
bankname: bank-b, item: item-b, id=2
bankname: bank-b, item: item-c, id=3
bankname: bank-b, item: item-d, id=4
bankname: bank-b, item: item-e, id=5
結果驗證ok,能正常使用動態庫;
4. 主應用程式不修改,修改動態庫的bank配置資料如下
static titem g_titem = ,
, ,, ,
//以下值是新增加的
, ,, };
add was used.
add: 9
sub was used.
sub: 7
mul was used.
mul: 6
div1 was used.
div: 4
bankname: bank-a, item: item-a, id=1
bankname: bank-a, item: item-b, id=2
bankname: bank-a, item: item-c, id=3
bankname: bank-a, item: item-d, id=4
bankname: bank-a, item: item-e, id=5
bankname: bank-a, item: item-f, id=6
bankname: bank-a, item: item-g, id=7
bankname: bank-a, item: item-h, id=8
bankname: bank-b, item: item-a, id=1
bankname: bank-b, item: item-b, id=2
bankname: bank-b, item: item-c, id=3
bankname: bank-b, item: item-d, id=4
bankname: bank-b, item: item-e, id=5
bankname: bank-b, item: item-f, id=6
結果驗證ok,能正常執行。
5. 總結
dlopen動態載入動態庫
為了使程式方便擴充套件,具備通用性,可以採用外掛程式形式。採用非同步事件驅動模型,保證主程式邏輯不變,將各個業務已動態鏈結庫的形式載入進來,這就是所謂的外掛程式。linux提供了載入和處理動態鏈結庫的系統呼叫,非常方便。本文先從使用上進行總結,涉及到基本的操作方法,關於動態鏈結庫的本質及如何載入進來...
Linux 動態裝載庫(dlopen)
linux有時我們需要在執行時指定庫的路徑去載入庫,而不是依賴於系統自動動態鏈結。比如說我們在需要做到動態載入庫外掛程式時就會用到動態裝載庫的特性 比如像lighthttpd和nginx的動態mod功能 linux提供了函式來幫助我們做到這件事,主要的幾個函式為 dlopen,dlsym,dlclo...
dlopen動態函式庫的載入。
前言 如論在linux上程式設計還是在windows上程式設計,為了程式的可擴充套件性,很多地方都用到了動態庫的載入。這裡來談談linux下的程式的動態函式庫的建立和載入。建立動態庫 在linux下邊編譯成so庫,gcc fpic shared c o lib so int add int a,in...