C++回调类函数
我使用Arduino IDE和东西网络arduino库来创建一个LoRa mote。C++回调类函数
我创建了一个应该处理所有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);
但是正如我此前的预期没有一次成功。
I通过使消息功能成为课程之外的正常功能来解决问题。不知道这是否是一种好的做法 - 但它有效。
// 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);
}
你应该将参数传递给按摩的原型表示:
void message(const uint8_t *payload, size_t size, port_t port);
由于按摩返回void,应该probabaly不能作为参数传递给其他的功能。
您试图在不使用类成员的情况下调用成员函数(即,属于类类型成员的函数)。这意味着,你通常会做什么是实例化类LORA的成员,然后再调用它:
LoRa loraMember;
loraMember.message();
既然你想调用该函数从类本身里面,没有一个成员类调用init(),你必须做出的功能的静态,如:
static void message(const uint8_t *payload, size_t size, port_t port);
然后你就可以在任何地方,只要它是公共使用LORA ::消息(),但调用它,就像这将使你的另一个编译器错误,因为消息的接口要求“const uint8_t * payload,size_t size,port_t port”。所以,你必须做的就是呼叫消息,如:
LoRa::message(payloadPointer, sizeVar, portVar);`
当你调用ttn.onMessage(functionCall)发生的事情是,该函数调用获取评估,然后由该函数返回什么被放放入圆括号中,然后用那个函数调用ttn.onMessage。由于你的LoRa :: message函数什么都没有返回(void),你会在这里得到另一个错误。
我建议在C++基础知识一本好书,让你开始 - book list
祝你好运!
非静态成员函数需要调用* object *。如果您没有对象,则不能使用非静态成员函数。一旦你有一个对象,我建议你看看['std :: function'](http://en.cppreference.com/w/cpp/utility/functional/function)和['std :: bind']( http://en.cppreference.com/w/cpp/utility/functional/bind)。 –