I'm trying to use a class function (interrupt service routine),
void (ClassName::*fp)(void)=ClassName::FunctionName;
and attaching it to an Arduino interrupt pin using the function with the following type inputs but that doesn't work.
void attachInterrupt(int, void (*)(void),int);
How can I make this happen? The interrupt service routine (ISR) needs to access privat object data, so I can't make a function outside of the class.
My compiler error:
ClassName.cpp : : In constructor 'ClassName::ClassName()':
ClassName.cpp : *)()'
ClassName.cpp : *)()' to 'void (*)()' for argument '2' to 'void attachInterrupt(uint8_t, void (*)(), int)'
Note: I am looking for a solution inside the class and will accept the answer that shows me a solution or shows me it's not possible.
Each class member function has an implicit first parameter that is the
this
pointer, so your method in fact is not with void paramter list - it takes one parameter-- the instance it is invoked on.You can use
boost::function<>
orboost::bind<>
to point to a class member function:If the function is not
static
, you cannot pass it in input to a function that accepts a non-member function pointer.Consider that a non-
static
member function has an implicit pointer toClassName
as its first parameter, which points to the object on which the member function is being invoked.Here, not even
std::bind()
will work, because the result is not convertible to a function pointer. Lambdas are convertible to function pointers, but only if they are non-capturing (and a lambda here would need to capture the object to invoke the member function on).Therefore, the only (ugly) workaround is to have a global adapter function which invokes the member function on an object which is available through a global pointer variable. The global pointer variable is set prior to calling the function:
If you want, you can make this slightly more flexible by turning
bar_adapter
into a function template, and passing the pointer-to-member-function as a template argument:Here is how you would use it:
Finally, here is a live example.