You can chat about native SDK questions and issues here.
User avatar
By alex323qp
#68250 Hi guys, I'm new to the ESP8266 world and just started working with the NONOS-SDK.

I'm writing my own libraries in c++ and got stuck trying to define the callbacks for a few network events. I've been trying to find ways around it but no luck so far.

Normally in C you would do:
Code: Select allvoid onConnected(void *args){...}

void connect(){
   struct espconn *conn = (struct espconn *) os_zalloc(sizeof(struct espconn));
   // ...
   espconn_regist_connectcb(conn, (espconn_connect_callback) onConnected);
}


But since my callback is a member function I'm obviously getting a compilation error (error: converting from 'void (FooClass::*)(void*)' to 'espconn_connect_callback {aka void (*)(void*)}')

Is there any c++ expert out there that could throw some light on this? I basically need the following (or similar) to work:
Code: Select allvoid FooClass::onConnected(void *args){...}

void FooClass::connect(){
   struct espconn *conn = (struct espconn *) os_zalloc(sizeof(struct espconn));
   // ...
   espconn_regist_connectcb(conn, (espconn_connect_callback) onConnected);
}


Any help would be greatly appreciated!

A.
User avatar
By martinayotte
#68254 As the title says "non-static" member function can't be use as a plain C callback, because the signature doesn't match and there is no "this" of the object passed to the callback.
Some more details here : https://stackoverflow.com/questions/240 ... d-in-class
The workaround is to make this method static, but in such case, you won't be able to access the object data members unless you have a global pointer to a singleton.
User avatar
By lethe
#68278 In a non-embedded environment, the solution to this issue is using std::bind() (or boost::bind() pre C++11) to get a function pointer from a member function of an instance of your object.

However since you probably don't want to use a stdlib or boost in an embedded environment, you'll have to resort to a workaround.
Instead of a function pointer, using a lambda that captures the object's this pointer may work.

A cleaner solution is to create a static function (global, not a class member) with C-linkage that gets a pointer to the object as an argument and calls your callback handler using that pointer (irrc the espconn struct has a void pointer "reverse" [sic] that can be used for that purpose, but you should double check).