我是 arduino 和编程的新手。 我在 arduino 中的我自己的库中包含了一个库,但第一个库包含一个以指针函数作为参数的函数。它是一个中断服务例程(ISR),但当中断发生时我需要调用我的 cpp 文件中的函数。所以我需要将该函数的指针传递给第一个库代码。当我在 .ino 文件中使用它时效果很好,我可以像这样传递它,
attachInterrupt(functionISR_name);
但是当我在 .cpp 文件中使用它时,出现错误。我的功能是这样的,
void velocity::functionISR_name(){
//some code
}
但是我怎样才能将这个函数的指针传递给第一个库函数呢?我尝试了这种方法,但出现错误,
attachInterrupt(velocity::functionISR_name);
最佳答案
您不能将方法传递给需要函数的函数,除非将其定义为静态。
将其写入静态:
static void velocity::functionISR_name()
和
attachInterrupt(&velocity::functionISR_name);
不幸的是,静态方法不再绑定(bind)到特定实例。您应该仅将它与单例一起使用。在 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 需要更多参数)并复制并粘贴错误消息。通常错误就发生在你不怀疑的地方。这个问题是个异常(exception)。通常我和其他人会要求更好的规范。
关于c++ - 使用范围解析运算符传递函数指针arduino,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195720/