Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
9 years, 5 months ago.
callback to class - member function - can't quite make it work...
Hi C++ experts, I'm struggling. I found examples, none quite match my needs, so tried to derive a solution - but to no success.
The comments below reflect the compiler output.
#include "mbed.h" class Callback { public: template <typename T> Callback(T * tptr, int (T::*mptr)(char * p), size_t allocsize) { m_size = allocsize; m_fp.attach(tptr, mptr); // No instance of overloaded function mbed::FunctionPointerArg1::attach[with R=void] // matches the argument list m_fp.attach(tptr, mptr); } void doit(void) { int x = 3; printf("size is %d\r\n", m_size); x = m_fp.call("hello"); // Too many arguments in function call x = m_fp.call("hello"); // A value of type "void" cannot be assigned to an entity of type int x = m_fp.call("hello"); printf("callback returned %d\r\n", x); } private: size_t m_size; FunctionPointer m_fp; }; class Worker { public: Worker() { } int Process(char * p) { printf("Process(%s)\r\n", p); return 7; } }; int main() { Worker wk; Callback cb(&wk, &Worker::Process, 75); cb.doit(); }
Is it that "FunctionPointer" is restricted and it cannot match the signature of "int function(char *)"?
1 Answer
9 years, 5 months ago.
FunctionPointer only takes functions of type void function (void) There is an FPointer class https://developer.mbed.org/cookbook/FPointer that takes functions of type uint32_t function (uint32_t) which should do what you need if you cast the char* to a uint32_t. Or you could just create your own callback, it's not that complicated to do.