2013-01-20 20 views
3

我剛開始在Arduino中製作庫。我創建了一個名爲inSerialCmd的庫。我想調用一個名爲delegate()的函數,該函數在包含inSerialCmd庫之後在主程序文件stackedcontrol.ino中定義。從Arduino的庫中調用主程序中的函數

當我嘗試編譯,一個錯誤被拋出:

...\Arduino\libraries\inSerialCmd\inSerialCmd.cpp: In member function 'void inSerialCmd::serialListen()': ...\Arduino\libraries\inSerialCmd\inSerialCmd.cpp:32: error: 'delegate' has not been declared

做了一些搜索後,它似乎是添加範圍解析操作可能做的伎倆。所以我在delegate()之前添加了「::」,現在是「:: delegate()」,但是拋出了相同的錯誤。

現在我很難過。

回答

5

您不能也不應該直接從程序庫調用函數。記住一個重要方面,使一個庫到庫:

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); 
    ... 
+1

謝謝!這使事情更清楚。我將研究函數指針。 –

+0

不應該被setDelegate(someAction); ?? –

+0

是的,糾正了一些行動 – jdr5ca