您不能也不應該直接從程序庫調用函數。記住一個重要方面,使一個庫到庫:
A library does not depend on the specific application. A library can be fully compiled and packaged into the .a file without the existence of a program.
所以有單向依賴,程序依賴於庫。乍一看可能會阻止你實現你想要的。您可以通過有時稱爲回調的方式來實現您所詢問的功能。主程序會在運行時向庫提供一個指向要執行的函數的指針。
// in program somwehere
int myDelegate(int a, int b);
// you set this to the library
setDelegate(myDelegate);
您在Arduino的,如果你看一下安裝如何中斷處理程序看到這一點。許多環境中都存在相同的概念 - 事件偵聽器,動作適配器 - 所有這些都有着相同的目標,允許程序定義庫無法識別的特定操作。
庫將通過函數指針存儲和調用函數。下面是這個樣子的粗略草圖:
// in the main program
int someAction(int t1, int t2) {
return 1;
}
/* in library
this is the delegate function pointer
a function that takes two int's and returns an int */
int (*fpAction)(int, int) = 0;
/* in library
this is how an application registers its action */
void setDelegate(int (*fp)(int,int)) {
fpAction = fp;
}
/* in libary
this is how the library can safely execute the action */
int doAction(int t1, int t2) {
int r;
if(0 != fpAction) {
r = (*fpAction)(t1,t2);
}
else {
// some error or default action here
r = 0;
}
return r;
}
/* in program
The main program installs its delegate, likely in setup() */
void setup() {
...
setDelegate(someAction);
...
謝謝!這使事情更清楚。我將研究函數指針。 –
不應該被setDelegate(someAction); ?? –
是的,糾正了一些行動 – jdr5ca