cocos2dx 的回调函数——函数指针
ocos2d-x中有大量的回调函数的应用,在ccobject.h中 有如下原型的函数:
typedef void (CCObject::*SEL_SCHEDULE)(float);
typedef void (CCObject::*SEL_CallFunc)();
typedef void (CCObject::*SEL_CallFuncN)(CCNode*);
typedef void (CCObject::*SEL_CallFuncND)(CCNode*, void*);
typedef void (CCObject::*SEL_CallFuncO)(CCObject*);
typedef void (CCObject::*SEL_MenuHandler)(CCObject*);
typedef void (CCObject::*SEL_EventHandler)(CCEvent*);
typedef int (CCObject::*SEL_Compare)(CCObject*);
#define schedule_selector(_SELECTOR) (SEL_SCHEDULE)(&_SELECTOR)
#define callfunc_selector(_SELECTOR) (SEL_CallFunc)(&_SELECTOR)
#define callfuncN_selector(_SELECTOR) (SEL_CallFuncN)(&_SELECTOR)
#define callfuncND_selector(_SELECTOR) (SEL_CallFuncND)(&_SELECTOR)
#define callfuncO_selector(_SELECTOR) (SEL_CallFuncO)(&_SELECTOR)
#define menu_selector(_SELECTOR) (SEL_MenuHandler)(&_SELECTOR)
#define event_selector(_SELECTOR) (SEL_EventHandler)(&_SELECTOR)
#define compare_selector(_SELECTOR) (SEL_Compare)(&_SELECTOR)
一般函数的函数名就是指针,不过是常量,再定义一个函数指针就是一个变量,这个变量可以指向这一类(注 是这一类)函数的地址;
上边的这种函数指针应该叫成员函数指针,跟C的那种全局的,静态的不一样的。
在项目中用法:先定义函数指针原型:(拿IAP举例)
typedef void (CCObject::*PorpBuyCallBack)(int resultCode,int propType); //IAP
typedef void (CCObject::*ShareManagerCallBack)(int resultCode,string shareType);//SHare
#define PROP_BUY_CALLFUNC(f) (PorpBuyCallBack)(&f)
#define SHARE_CALLFUNC(f) (ShareManagerCallBack)(&f)
#define GBM CCBillingManager::getBillingManager() //一个单例
CCBillingManager.h文件中:
bool buy(PROP* prop,CCObject* pTarget,PorpBuyCallBack pCallBack);
CCBillingManager.cpp文件中:
bool CCBillingManager::buy(PROP* prop,CCObject* pTarget,PorpBuyCallBack pCallBack)
{
m_pTarget = pTarget;
m_pPropBuyCallFunc = pCallBack;
m_pProp = prop;
goIAp---- 根据ios ,android 区分,
}
在IAP.mm中
-(void)billing:(bool)resultCode result: (string)consumName
{
GBM->buyResult(consumName, resultCode); //上边的GBM
}
void CCBillingManager::billingResult(PROP_ID id,int count,int resultCode)
{
if (m_pTarget && m_pPropBuyCallFunc)
{
(m_pTarget->*m_pPropBuyCallFunc)(resultCode,id);
}
}
然后在Shop中
定义一个void (int resultCode,int propType)类型的回调函数,把自己this传进去,最后。。。呵呵。估计没有说清楚。
网上一个人的http://www.cnblogs.com/worldtraveler/archive/2013/07/16/3193108.html不错。