我被困。我正在尝试形成一个函数,它将吃掉无类函数指针和对象中的函数指针。这是我当前的代码,希望能解释更多。
(它应该在 Arduino 上运行,所以我不能使用大型库。)
首先,我在 Arduino 上使用这个库:
/* SimpleTimer - A timer library for Arduino.
* Author: mrom[email protected] /cdn-cgi/l/email-protection
* Copyright (c) 2010 OTTOTECNICA Italy
*/
它采用在这种类型的设定定时器间隔上调用的函数:
typedef void (*timer_callback)(void);
据我所知,这是一个类函数,网页指向成员函数的指针 http://www.parashift.com/c++-faq-lite/pointers-to-members.html让我走得很远,但还不够远。可能是我这边的术语缺陷。
现在,我已经创建了自己的类,我想依次使用这个 SimpleTimer 库。但是,如果我向 SimpleTimer 提供我的类函数,它不喜欢它们(据我所知)。但是如何在不改变 SimpleTimer 库的情况下实现这一点呢?
所以就有了 Robot 类,它有Robot::halt()
。我希望机器人向前移动一定的时间。就像这样:
void Robot::forward(int speed, long time) {
reset();
timer.setTimer(time, c_func, 1);
analogWrite(l_a, speed);
analogWrite(r_a, speed);
isMoving(true);
}
void Robot::halt() {
__isMoving = false;
digitalWrite(r_a, LOW);
digitalWrite(r_b, LOW);
digitalWrite(l_b, LOW);
digitalWrite(l_a, LOW);
}
c_func 变量此时是一个无类函数,但我想使用Robot::halt
功能。我看过、读过、学习过,但还没有成功。我似乎无法理解这个问题,因为我错过了一些角度。
I tried:
timer.setTimer(time, (this->*halt), 1);
timer.setTimer(time, Robot::*halt, 1);
timer.setTimer(time, &Robot::halt), 1);
但这都会造成同样的问题/我只是在黑暗中刺伤......
EDIT
早些时候,我说过不想更改 SimpleTimer 库代码。我想重新讨论这个,我想改变它会是更好的选择。
感谢所有当前的答案,我只被允许将一个答案标记为可行的答案,实际上我在这里读到的所有内容都非常有帮助。
要继续此操作,请更改 SimpleTimer 代码。这个类需要引用保存我的“halt”函数的对象,对吧?那么,将 settimer 函数重载为将我的对象和我的函数作为两个单独的指针的东西会起作用......?我想我已经掌握了窍门,但是我的头脑还没有达到这个目标。
EDIT
我不知道谁又带来了这个,但是,任何人都找到了这个线程。如果发现成员函数指针和最快的 C++ 委托 http://www.codeproject.com/KB/cpp/FastDelegate.aspx对函数指针和成员函数指针进行了非常好的介绍。
EDIT
让它工作起来,更改 SimpleTimer 库以使用此委托系统:http://www.codeproject.com/KB/cpp/FastDelegate.aspx http://www.codeproject.com/KB/cpp/FastDelegate.aspx
它集成得非常好,如果 Arduino 库中有一个像这样的标准委托系统,那就太好了。
测试中的代码(工作)
typedef
typedef FastDelegate0<> FuncDelegate;
机器人类中的代码:
void Robot::test(){
FuncDelegate f_delegate;
f_delegate = MakeDelegate(this, &Robot::halt);
timer.setTimerDelg(1, f_delegate, 1);
}
void Robot::halt() {
Serial.println("TEST");
}
SimpleTimer类中的代码:
int SimpleTimer::setTimerDelg(long d, FuncDelegate f, int n){
f();
}
Arduino 在控制台中打印 TEST。
下一步将其放入数组中,不会发现太多问题。谢谢大家,我简直不敢相信我两天内学到的东西。
那是什么味道?那是……的味道吗?成功!
对于感兴趣的人来说,所使用的 Delegate 系统并不构成内存容量问题:
使用 FastDelegate
AVR Memory Usage
----------------
Device: atmega2560
Program: 17178 bytes (6.6% Full)
(.text + .data + .bootloader)
Data: 1292 bytes (15.8% Full)
(.data + .bss + .noinit)
Finished building: sizedummy
没有 FastDelegate:
AVR Memory Usage
----------------
Device: atmega2560
Program: 17030 bytes (6.5% Full)
(.text + .data + .bootloader)
Data: 1292 bytes (15.8% Full)
(.data + .bss + .noinit)
Finished building: sizedummy