Using an Object for Interrupt (and other) Call Backs

So, it seems at least weekly someone posts that they can’t use attachInterrupt() to attach an object’s instance function. The reason you can’t get a compliant pointer to an instance function has been discussed many times here and in other forums. This also applies to other code that uses callback functions.

It seems a really slick way to handle this would be to define an abstract “callback” class:

#ifndef CALLBACK_H_
#define CALLBACK_H_

class CallBack {
public:
	virtual void callback(void *ptr = nullptr) = 0;
	virtual ~CallBack() {
	}
};

#endif /* CALLBACK_H_ */

You’d then create your own classes that inherit from this and pass a pointer to the attach function. One example that comes to mind would be a class that handles rotary encoders using interrupts.

In theory, it should be fairly straight-forward adding the capability to use callback objects to the code that attaches, detaches, and services interrupts. You’d create an array of CallBack class pointers similar to the array of callback function pointers. The attachInterrupt() would be overloaded take a pointer to a CallBack object. A flag would be set for each interrupt to tell the ISR vector function whether to use the CallBack object or the standard callback function.

Well, that’s the theory. The first problem I see is files that contain the interrupt-related code, such as:

ESP8266 -- core_esp8266_wiring_digital.c
Arduino M0 -- WInterrupts.c (in SAMD Core)
AVR -- WInterrupts.c (in AVR Core)
Teensy -- pins_teensy.c

These are obviously all .c files. Thus, it doesn’t seem the above idea would work in them as it requires C++ techniques. So, the first question is do they have to be .c files? I don’t know enough about the nuances involved with how the tool chain compiles and links C code verses C++ code to know.

After that, maybe the bigger question is if a change like this is even possible given inertia of the Arduino ecosystem and large number of board packages that would need to be modified. It doesn’t seem to me that the change would affect existing application code as the old attach method would still be available. But, not I don’t know how to tell for sure.

Anyway, I’m just throwing it out there because of the vast breadth and depth of experience people on this forum have. Maybe it has been considered already and deemed impractical / impossible.