簡體   English   中英

將函數指針從 Arduino 傳遞給 C++

[英]Passing function pointer from Arduino to C++

這個問題是關於 C++,但它與 Arduino 交互,由於我不是軟件開發人員,我很樂意得到一些建議。

在 Arduino 中,用戶創建一個類的實例並設置其委托方法:

Arduino main program:

    //instance
    Main interpreter;
    //set delegate
      interpreter.setDelegate(intepreterDelegate);
    //delegate function
         float intepreterDelegate(char *arg){return 3;}

Main類然后創建另一個類的實例,稱為Sub ,因此:

Sub - > send delegate to Main-> send delegate to Arduino

Main確實通過以下方式成功地從 Sub獲取了委托消息:

Main.h

  //being called from the sub
   static float fromSubDelegate(char *arg){

        // *Here I am trying to push forward this delegate out to the user on arduino
        Main. b;   
        float result = (b.*b.fpAction)(arg);
        return  result;


     };

    float (Main.::*fpAction)(char*) = 0 ;
    void setDelegate( float(*fp)(char*));

問題出在我設置委托的Main.cpp

//arduino set this delegate of the main class .cpp
void Main.::setDelegate( float(*fp)(char*))
{

    fpAction = fp; // *gives error because fpAction is a member function

}

我已經提供了我擁有的所有數據。 我不是 C++ 程序員,因此我可能做錯了什么。

這不是你在另一個問題中問的。 您(似乎)在 adruino 代碼中執行的操作與您在 C++ 代碼中想要執行的操作之間存在不匹配。

您不能將委托從非成員函數更改為成員函數,並且您不能在它使用的類之外​​定義成員函數(即委托)。

你正在嘗試的東西目前沒有意義。 你的 arduino 定義了一個實例

Main interpreter;

然后它在解釋器實例中定義和設置委托(到目前為止還可以)。

但是在 fromSubDelegate() 中,您創建了一個新實例 b。 您在解釋器實例中設置的任何委托都不會在 b 實例中設置,除非函數指針是靜態的,但在這種情況下,您甚至不需要 fromSubDelegate() 函數,您只需調用函數指針即可直接。

你似乎對事情的運作方式有一個錯誤的想法。 要帶回家的是,如果您有一個類的非靜態成員函數,則有一個隱藏的額外參數,您可以在函數中將其用作“this”。 所以你定義的成員函數

class X
{
    void func(int i);
}

不一樣

void func (int i);

在類之外定義。 真的更像void

func(X* this, int i); 

盡管這在語義上是“正確的”,但在語法上卻並非如此。

感謝oreubens的幫助,我找到了一個解決方案 - 只是直接從 main 傳遞到 sub,函數的指針,所以:

void Main::setDelegate( float(*fp)(char*))
{
    fpAction=fp;
    sub->setDelegate(fpAction);



}

效果很好。 再次感謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM