[英]C++ callback to class function
我正在使用Arduino IDE和物联网arduino库创建LoRa节点。
我创建了一个应处理所有与LoRa相关的功能的类。 在此类中,如果我收到下行消息,则需要处理回调。 ttn库具有我要在init函数中设置的onMessage函数,并解析另一个函数,它们是一个类成员,称为message。 我收到错误“无效使用非静态成员函数”。
// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>
TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);
LoRa::LoRa(){
}
void LoRa::init(){
// Set the callback
ttn.onMessage(this->message);
}
// Other functions
void LoRa::message(const uint8_t *payload, size_t size, port_t port)
{
// Stuff to do when reciving a downlink
}
和头文件
// File: LoRa.h
#ifndef LoRa_h
#define LoRa_h
#include "Arduino.h"
#include <TheThingsNetwork.h>
// Define serial interface for communication with LoRa module
#define loraSerial Serial1
#define debugSerial Serial
// define the frequency plan - EU or US. (TTN_FP_EU868 or TTN_FP_US915)
#define freqPlan TTN_FP_EU868
class LoRa{
// const vars
public:
LoRa();
void init();
// other functions
void message(const uint8_t *payload, size_t size, port_t port);
private:
// Private functions
};
#endif
我努力了:
ttn.onMessage(this->message);
ttn.onMessage(LoRa::message);
ttn.onMessage(message);
但是他们都不如我预期的那样工作。
您试图在不使用类成员的情况下调用成员函数(即,属于类类型成员的函数)。 这意味着,您通常要做的是首先实例化类LoRa的成员,然后按以下方式调用它:
LoRa loraMember;
loraMember.message();
由于您试图从类内部调用该函数,而没有类的成员调用init(),因此必须使该函数静态化,例如:
static void message(const uint8_t *payload, size_t size, port_t port);
然后,只要它是公共的,就可以在任何地方使用LoRa :: message(),但是那样调用它会给您带来另一个编译器错误,因为消息的界面要求“ const uint8_t *有效载荷,size_t大小,port_t端口” 。 因此,您需要做的是呼叫消息,例如:
LoRa::message(payloadPointer, sizeVar, portVar);`
当您调用ttn.onMessage( functionCall )时,将对函数调用进行求值,然后将该函数返回的内容放在括号中,并以此调用ttn.onMessage。 由于您的LoRa :: message函数不返回任何内容(无效),因此您将在此处收到另一个错误。
我建议一本有关C ++基础知识的好书来帮助您入门- 图书清单
祝好运!
您应该按照原型指示将参数传递给按摩:
void message(const uint8_t *payload, size_t size, port_t port);
由于按摩返回无效,因此不应将其用作其他函数的参数。
我通过使消息函数成为类之外的普通函数来解决了该问题。 不知道这是否是个好习惯-但这行得通。
// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>
TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);
void message(const uint8_t *payload, size_t size, port_t port)
{
// Stuff to do when reciving a downlink
}
LoRa::LoRa(){
}
void LoRa::init(){
// Set the callback
ttn.onMessage(message);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.