0

I use a library which has these definitions

typedef void (*CallbackFunction) (ESPRotary&);
void ESPRotary::setChangedHandler(CallbackFunction f) { ... }

When I try to use the setChangedHandler function I get an issue that the definition of my callback is wrong.

#pragma once

#include "ESPRotary.h"

class MyUsermod : public Usermod
{
private:
  ESPRotary r = ESPRotary(13, 12);

public:
  void rotate(ESPRotary &r)
  {
    Serial.println(r.getPosition());
  }

  void setup()
  {
    // argument of type "void (MyUsermod::*)(ESPRotary &r)" is incompatible 
    // with parameter of type "ESPRotary::CallbackFunction"C/C++(167)
    r.setChangedHandler(rotate); 
  }
};

What am I doing wrong?

boop
  • 7,413
  • 13
  • 50
  • 94

2 Answers2

1
void rotate(ESPRotary &r)

This is not a function. This is a (non-static) class method. This is declared as a member of class MyUsermod, something that's completely different from declaring a function named rotate() is some randomly-chosen .cpp file, with no further context.

Class methods require instances of classes to be invoked for. The type of rotate is

void (MyUsermod::*) (ESPRotary&)

and not

void (*) (ESPRotary&)

and this answers the reason for the compilation error, and the type mismathc.

As far as how to fix it, there is no uniform solution for every instance of this issue. It depends entirely on how these objects are used in the rest of your program. The most flexible solution is to change CallbackFunction to be the correct type, and then decide whose class instance's method will be invoked in the code that invokes the callback.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
1

The callback function needs to be defined statically when defined inside the class:

class MyUsermod : public Usermod
{
private:
  ESPRotary r = ESPRotary(13, 12);

public:
  /* Callback function "static" defined */
  static void rotate(ESPRotary &r)
  {
    Serial.println(r.getPosition());
  }

  void setup()
  {
    r.setChangedHandler(rotate); 
  }
};
References
Sercan
  • 4,739
  • 3
  • 17
  • 36