【问题标题】:Passing function pointer with scope resolution operator arduino使用范围解析运算符arduino传递函数指针
【发布时间】:2013-10-05 08:37:38
【问题描述】:

我是 arduino 和编程的新手。 我在我自己的 arduino 库中包含了一个库,但是第一个库包含一个函数,该函数具有一个指针函数作为参数。这是一个中断服务程序(ISR),但是当发生中断时我需要在我的 cpp 文件中调用一个函数。所以我需要将该函数的指针传递给第一个库代码。当我在 .ino 文件中使用它时效果很好,我可以像这样传递它,

attachInterrupt(functionISR_name);

但是当我在 .cpp 文件中使用它时,我得到了错误。我的功能是,

void velocity::functionISR_name(){
//some code
}

但是我怎样才能将这个函数的指针传递给第一个库函数呢?我尝试过这种方式但出现错误,

attachInterrupt(velocity::functionISR_name);

【问题讨论】:

  • “我收到错误”。有什么错误?

标签: c++ c header arduino


【解决方案1】:

您不能将方法传递给需要函数的函数,除非您将其定义为静态的。

写成静态的:

static void velocity::functionISR_name() 

attachInterrupt(&velocity::functionISR_name);

不幸的是,静态方法不再绑定到特定实例。您应该只将它与单例一起使用。在 Arduino 上,您应该在代码中编写如下所示的类:

class velocity
{
    static velocity *pThisSingelton;
 public:
    velocity()
    {
      pThisSingelton=this;
    }

    static void functionISR_name()
    {
      pThisSingelton->CallWhatEverMethodYouNeeded();
      // Do whatever needed.
    }

   // … Your methods
};

velocity *velocity::pThisSingelton;
velocity YourOneAndOnlyInstanceOfThisClass;

void setup()
{
  attachInterrupt(&velocity::functionISR_name);

  // …other stuff…
}

这看起来很难看,但在我看来,Arduino 完全没问题,因为这样一个系统的机会非常有限。

再想一想,我个人会选择索林在上面的回答中提到的方法。那会更像这样:

class velocity
{
 public:
    velocity()
    {
    }

    static void functionISR_name()
    {
      // Do whatever needed.
    }

   // … Your methods
};

velocity YourOneAndOnlyInstanceOfThisClass;

void functionISR_name_delegation()
{
  YourOneAndOnlyInstanceOfThisClass.functionISR_name();
}

void setup()
{
  attachInterrupt(functionISR_name_delegation);

  // …other stuff…
}

它还可以为您在第一个示例中所需的指针节省一些字节。

作为站点说明:对于将来,请发布确切的代码(例如 attachInterrupt 需要更多参数)并复制并粘贴错误消息。通常错误在你不怀疑的地方是准确的。这个问题是个例外。通常我和其他人会要求更好的规范。

【讨论】:

    【解决方案2】:

    您将指针传递给函数,但该函数是类成员。调用可能无效,因为 this 指针将是垃圾(可能编译得很好,但会在运行时抛出奇怪的错误)。

    您需要在任何类之外定义一个普通的普通函数并使用它。 如果您没有一个非常复杂的项目,您可以使用一个指向您应该使用的类实例的全局指针而侥幸,只需将调用委托给您的新函数。 如果你想以正确的方式做事,你需要一些机制来获取我上面谈到的实例指针。通常这涉及到单例或一些工厂模式。

    例子:

    class Foo {
      void method() {
        x = 5;
      }
      int x;
    }
    

    对方法进行回调会崩溃,因为您有一个无效的指向 this 的指针,因此 x=5 将在内存中随机写入 5。 你需要的是这样的:

    static Foo* foo_instance;  // Initialized somewhere else.
    void method_delegator() {
      foo_instance->method();
    }
    

    现在您可以将method_delegator 传递给函数。它会起作用,因为您现在还通过 foo_instance 获取 this 指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 2010-09-09
      • 2021-12-27
      • 2018-05-14
      • 1970-01-01
      • 2014-10-05
      相关资源
      最近更新 更多