【问题标题】:Call function in main program from a library in Arduino从 Arduino 的库中调用主程序中的函数
【发布时间】:2013-01-03 20:59:45
【问题描述】:

我刚刚开始在 Arduino 中制作库。我创建了一个名为 inSerialCmd 的库。在包含 inSerialCmd 库之后,我想调用在主程序文件stackedcontrol.ino 中定义的名为delegate() 的函数。

当我尝试编译时,抛出一个错误:

...\Arduino\libraries\inSerialCmd\inSerialCmd.cpp:在成员函数中 '无效 inSerialCmd::serialListen()': ...\Arduino\libraries\inSerialCmd\inSerialCmd.cpp:32: 错误: 'delegate' 尚未声明

经过一番搜索后,似乎添加范围解析运算符可能会奏效。所以我在delegate()之前添加了“::”,现在是“::delegate()”,但是还是抛出了同样的错误。

现在我被难住了。

【问题讨论】:

    标签: class function scope call arduino


    【解决方案1】:

    您不能也不应该直接从库中调用程序中的函数。请记住使图书馆成为图书馆的关键方面:

    库不依赖于特定的应用程序。一个库可以在不存在程序的情况下完全编译并打包到 .a 文件中。

    所以有一个单向依赖,一个程序依赖于一个库。乍一看,这似乎会阻止你实现你想要的。您可以通过有时称为回调的方式来实现您所询问的功能。主程序将在运行时向库提供一个指向要执行的函数的指针。

    // 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 这是一个多么棒的答案。最好的之一。希望我能给你加分。
    猜你喜欢
    • 2015-08-07
    • 1970-01-01
    • 2016-03-04
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 2019-06-30
    相关资源
    最近更新 更多