我在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