class 函数的 C++ 回调

C++ callback to class function

我正在使用 Arduino IDE 和 things network arduino 库来创建 LoRa 节点。

我创建了一个 class 来处理所有与 LoRa 相关的功能。在此 class 中,如果我收到下行消息,我需要处理回调。 ttn 库有 onMessage 函数,我想在我的 init 函数中设置它并解析另一个函数,它是一个 class 成员,称为消息。 我收到错误 "invalid use of non-static member function"。

// 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);

然而 none 他们的工作如我所料。

您应该按照其原型所示将参数传递给 massage

void message(const uint8_t *payload, size_t size, port_t port);

由于massage returns 无效,因此不应将其用作其他函数的参数。

您试图在不使用 class 成员的情况下调用成员函数(即属于 class 类型成员的函数)。这意味着,您通常要做的是先实例化 class LoRa 的一个成员,然后像这样调用它:

LoRa loraMember;    
loraMember.message();

由于您试图从 class 本身内部调用该函数,而没有 class 的成员调用 init(),因此您必须使该函数静态化,例如:

static void message(const uint8_t *payload, size_t size, port_t port);

然后你可以在任何地方使用 LoRa::message() 只要它是 public,但是像那样调用它会给你另一个编译器错误,因为 message 的接口要求“const uint8_t *有效负载,size_t 大小,port_t 端口”。所以你要做的就是像这样调用消息:

LoRa::message(payloadPointer, sizeVar, portVar);`

当你调用 ttn.onMessage(functionCall) 时,函数调用被求值,然后该函数返回的内容被放入括号和 ttn.onMessage 被调用。由于你的 LoRa::message 函数 returns 什么都没有(无效),你会在这里得到另一个错误。

我推荐一本关于 C++ 基础的好书来帮助你入门 - book list

祝你好运!

我通过将消息函数设为 class 之外的普通函数解决了这个问题。不确定这是否是好的做法 - 但它有效。

// 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);
}