我在 Arduino 程序中使用来自 Github 的“PacketSerial”库。在库提供的示例中,所有内容都在 loop() 或 setup() 中。我想将所有这些移至实例“arDriver”,但遇到了一些麻烦..
我这样初始化它,效果很好(就像提供的示例一样);
//in app.ino
void setup()
{
arDriver.setup(); //<- I want to move the 2 functions below in here
arDriver.myPacketSerial.begin(115200);
arDriver.myPacketSerial.setPacketHandler([](const uint8_t* buffer, size_t size)
{
arDriver.communicationCOBS(arDriver.myPacketSerial, buffer, size);
});
}
//in ArduinoDriver.cpp
void ArduinoDriver::communicationCOBS(const PacketSerial& sender, const uint8_t* buffer, size_t size)
{ ... }
//in PacketSerial.h
typedef void (*PacketHandlerFunction)(const uint8_t* buffer, size_t size);
void setPacketHandler(PacketHandlerFunction onPacketFunction)
{ ... }
当我将 2 个 PacketSerial 函数移动到 arDriver::setup() 中时,我得到以下信息;(在解决了我需要捕获 [this] 的错误之后)
void ArduinoDriver::setup()
{
...
myPacketSerial.begin(115200);
myPacketSerial.setPacketHandler([this](const uint8_t* buffer, size_t size)
{
communicationCOBS(myPacketSerial, buffer, size);
});
}
现在我得到以下我无法解决的错误;
错误(活动)E0304 没有重载函数实例“PacketSerial_::setPacketHandler [with EncoderType=COBS, PacketMarker=(uint8_t)'\000', ReceiveBufferSize=256U]”匹配参数列表参数类型为:(lambda []void ( const uint8_t *buffer, size_t size) -> void) 对象类型为:PacketSerial
我发现了几个关于类似问题的帖子和问题,但缺乏在我的特定应用程序中实现这些的技能或知识。下面是我认为最有希望的,但到目前为止,我无法让它工作。我不喜欢使用基于 std::function 的解决方案
// from: https://bannalia.blogspot.com/2016/07/passing-capturing-c-lambda-functions-as.html
void do_something(void(*callback)(void*),void* callback_arg)
{
...
callback(callback_arg);
}
int num_callbacks=0;
...
auto callback=[&](){
std::cout<<"callback called "<<++num_callbacks<<" times \n";
};
auto thunk=[](void* arg){ // note thunk is captureless
(*static_cast<decltype(callback)*>(arg))();
};
do_something(thunk,&callback);
output: callback called 1 times