如何将指向typedef函数的指针作为参数传递?

时间:2015-09-13 14:47:12

标签: c pointers arduino typedef

我正在努力改善PJON内部如何触发反应。这是Arduino的通信总线系统我用c:https://github.com/gioblu/PJON

写的

我很难定义一个指向新类型函数(typedef)的指针,它接收一个int(长度)和一个指向字节数组的指针(* payload):

在.h文件中,我声明了接收器类型函数:

typedef void (* receiver)(uint8_t length, uint8_t *payload);

PJON类还包含:

receiver _receiver;

setter会让用户设置自动调用的函数:

void PJON::set_receiver(receiver *r) {
  _receiver = r;
}

用户只需声明函数:

receiver led_blink(uint8_t length, uint8_t *payload) {
  digitalWrite(13, HIGH);
  delay(30);
  digitalWrite(13, LOW);
  Serial.println("SUCCESS");
};

并将其传递给setter:

network.set_receiver(led_blink);

当系统收到消息时:

this->_receiver(data[1] - 4, data + 2); 

调用传递实际参数的函数。

这是我从编译器收到的错误消息:

PJON.ino: In function 'void setup()':
PJON.ino:14:33: error: no matching function for call to 'PJON::set_receiver(void (* (&)(uint8_t, uint8_t*))(uint8_t, uint8_t*))'
PJON.ino:14:33: note: candidate is:
In file included from PJON.ino:1:0:
C:\Users\gio\Desktop\Arduino Software\arduino-1.6.0\libraries\PJON/PJON.h:115:10: note: void PJON::set_receiver(void (**)(uint8_t, uint8_t*))
     void set_receiver(receiver *r);
          ^
C:\Users\gio\Desktop\Arduino Software\arduino-1.6.0\libraries\PJON/PJON.h:115:10: note:   no known conversion for argument 1 from 'void (*(uint8_t, uint8_t*))(uint8_t, uint8_t*) {aka void (*(unsigned char, unsigned char*))(unsigned char, unsigned char*)}' to 'void (**)(uint8_t, uint8_t*) {aka void (**)(unsigned char, unsigned char*)}'

我无法理解错误在哪里!!

1 个答案:

答案 0 :(得分:1)

typedef void (* receiver)(uint8_t length, uint8_t *payload);

这将标识符receiver定义为具有给定签名的函数的指针的类型(请注意typedef中的星号)。所以

void PJON::set_receiver(receiver *r) {
    _receiver = r;
}

实际上会期望一个指向函数指针的指针。 (在这里留下星号,它应该表达你最初的意思)

我可以肯定地说,只要这与C和/或C ++兼容...... arduino有自己的(有点类似的)语言,正如评论中已经指出的那样 - 它&# 39; s仍然是另一种语言。