C 動態呼叫共享庫函式

2021-05-18 00:53:09 字數 758 閱讀 9976

1. 需求.

我們需要呼叫乙個函式

std::string getvalue(int index)

這個函式定義在庫t1.so裡面

2. t1.so

#:cat t1.c

#include

extern "c"

std::string getvalue(int index)

}#: cc -g t1.c -o t1.so

3. 用法

#: cat t2.c

#include

#include

#include

#include

using namespace std;

std::string (*getvalue)(int index);

// 這種定義方式, 和std::string (*func)(int index);是乙個意思, c++函式名被mangle成乙個字串, 只要t1.so裡面的函式名被宣告成getvalue, 就可以通過dlsym(...)得到, 然後賦給func變數。

// extern "c"

if ((getvalue=(std::string (*)(int))dlsym(lib, "getvalue"))==null)

std::string ret = getvalue(2);

cout << ret << endl;

}#: cc t2.c -o t2

上面程式片在sun studio 11編譯通過。

Lua呼叫只有標頭檔案的C 動態庫函式

前段時間公司讓我尋找乙個for c 的lua binder庫,要求c 和 lua能夠雙向呼叫 所以swig tolua排除 最後選擇了luabind的乙個fork,名叫luaponte,選擇的原因是既有luabind的廣泛使用比較可靠,又支援luajit 我們要用 的5.1語法。昨天做summary...

C語言 呼叫的動態庫函式重名問題分析

設計兩個動態庫 第乙個動態庫 libhelloc func1.h ifndef func1 h define func1 h int func1 void func endif func1.c include func1.h int func1 void func libhelloc.h ifnde...

C 呼叫C庫函式詳細講解

c 呼叫c庫函式詳細講解 2011年03月03日 c 呼叫c庫函式詳細講解 undefined reference to 出現問題的原因是c庫函式編譯成obj檔案時對函式符號的處理和c 不同。因為c 函式支援過載,所以函式符號的處理要更複雜一些,c往往不作修飾。例如有函式 dofunc.c incl...