I am trying to call a function in the main sketch when doing certain action inside the library.
Function prototype is:
void MessageAdmin(char *Message)
And I found this is not an easy action at all. I tried adding a Delegate function with help from the answer here: class - Call function in main program from a library in Arduino - Stack Overflow without success, mostly compiling but in the end I get "undefined reference to `Lib::setDelegate(void ()(char))'". I have no experience with function pointers, I suspect I am not adding the function in the right place inside the library header file. Is there any general approach to this?
TIA
If I understand this, surely that is the wrong way round of doing things. Your main sketch 'gets' from a library. The library should not be aware of your main sketch, and should not call into it, should it?
Steve
A proper way to do this is via callback interface.
setup your library to have a public method which is called from the main sketch and add the callback for later use.
YourLibrary.h
//YourLibrary
class YourLibrary
{
using m_cb = void (*)(char*); //alias function pointer
private:
m_cb action;
public:
void add_callback(m_cb act)
{
action = act;
}
void process()
{
//do stuffs
char message[] = "Hello World";
action(message); //invoke the callback
}
};
main_sketch.ino
//main_sketch.ino
#include "YourLibrary.h"
YourLibrary lib; //create instance of YourLibrary
void MessageAdmin(char *Message)
{
}
void setup()
{
lib.add_callback(MessageAdmin); //add MessageAdmin method to the library to be called later.
}
@steve1001 Yes, maybe I should do the other way around, but I am handling an http server with the lib, and I need to call that function in the main sketch somehow based on actions done on the page.
@arduino_new THANK YOU! That was quick, and I think this is what I need!!! I will try and post back results!
@arduino_new the callback worked a treat! THANKS AGAIN!!!!