Passing Object function as callback

Hi guys,

im working with my first classes and now i want to pass a function as callback but i dont get it to work. The Code:

NETSerial.h

class NETSerial {
private:
    void (*iCallback)(char[]);
    void processIncoming();

public:
    NETSerial();
   
    void onReceive(void (*callback)(char[]));
};

NETSerial.cpp

void NETSerial::onReceive(void (*callback)(char[]))
{
	iCallback = callback;
}

void NETSerial::processIncoming()
{
.......
	// Callback
	iCallback(receivedData);

}

NETController.h

class NETController {
private:

public:
    NETController();

    void onSerialRec(char msg[]);
};

NETController.cpp

void NETController::onSerialRec(char msg[]) {

	Serial.print("Conroller callback=>");;
	Serial.println(msg);

}

Programm.ino

// Serial
NETSerial USBSerial = NETSerial();

// Controller
NETController Controller = NETController();


void setup() {

     // THIS WORKS
    USBSerial.onReceive(&test);

   // THAT DONT WORK
   USBSerial.onReceive(&Controller.onSerialRec);

}


void loop(){


}


void test(char msg[]) {

    Serial.print("Callback msg=>");
    Serial.println(msg);

    Controller.onSerialRec(msg);
}

As you can see i can pass a function declared in the main ino file like my "test" function. But i cant pass a function from an object of my NETController class.

The original classes are much bigger but i stripped that all out. Hope my code is ok to describe my problem.

Best regards,

Raphael

pass the object

If you know which method to call beforehand, then what @Juraj suggested seems to be the way to go.

Otherwise, you might want to have a look at pointers to member functions. For example,

class C {
public:
  void print() {
    Serial.println("Hi.");
  }
};

void test(C& obj, void (C::*f)()) {
 (obj.*f)();
}

void setup() {
  Serial.begin(9600);

  C c;
  test(c, &C::print);  // Prints "Hi.".
}