I am currently designing a game using Cocos2dx. I am looking to develop an API for my Game with callbacks using the callfuncND_selector function. I want something similar to the the HTTPRequest function setCallBackFunction that takes a function as a pointer
request->setResponseCallback(this,callfuncND_selector(MenuLayer::onHttpRequestCompleted));
Can anyone show me how i can do this ? Like flesh out the function definintion to help me ? I am new to c++ and any help would be much appreciated.
Kind Regards
I assume you are asking about how to declare such a function?
One example, if you are sure the target callback selector remains in memory, like so:
In your hpp:
class YourRequestClass
{
// ...
protected:
CCCallFuncND* stored_cb ;
void executeStoredCallback() ;
void releaseCallback() ;
public:
void setResponseCallback( CCCallFuncND* cb ) ;
// ...
}
In your cpp:
void YourRequestClass::setResponseCallback( CCCallFuncND* cb )
{
// store cb for later use. You have to retain it for it to stick around.
if ( cb )
{
cb->retain() ;
stored_cb = cb ;
}
}
void YourRequestClass::executeStoredCallback()
{
if ( stored_cb ) stored_cb->execute() ;
}
void YourRequestClass::releaseCallback()
{
if ( stored_cb ) { stored_cb->release() ; stored_cb = NULL ; }
}
To call your function, from your "request" instance, and "this" being the owner instance of the callback method:
request->setResponseCallback( cocos2d::CCCallFuncND::create( this, (cocos2d::SEL_CallFuncND) &yourcbclassname::your_cb_method, (void*)ptr_to_some_data ) ) ;
This shows you how you might go about declaring a cocos2d cb parameter. The big caveat is that this approach would not be suitable if the cb object instance is not guaranteed to stick around in memory, otherwise you would end up playing with dangling pointers.
If you goal is a general purpose API rather than a specific case for a specific project, you would need another approach to deal with retention (say, smartptr and your own functor system, for instance).
Hope this helps.