I came across the following code while debugging. I was able to get the result correctly but I didn’t not understand the function pointers defined in here.
Here pNewMsgeFunc is the alias name of the function pointer tNewMsg which is created inside the structure stRsStruct.
RsMsg.h
typedef RsMsg* (*tNewMsg)(void);
tNewMsg pNewMsgFunc;
typedef struct
{
int nMsgId;
NSString* sAsciiName;
tNewMsg pNewMsgFunc; // calls new for the particular message
} stRsStruct;
RsMsg.cpp
RsMsg(int uMessageId,tNewMsg pNewMsg,const char* szAsciiName,void* pData,
size_t uDataSize)
{
//intialisations
}
RsMsgDerived.h
#define DECLARE_NEWMSG(CssName,CssID) \
static CssName* FromMsg(RsMsg* pMsg) \
{ \
return dynamic_cast<CssName*>(pMsg); \
} \
static RsMsg* NewMsg() \
{ \
return new CssName; \
} \
enum {ID = CssID}; \
Its said that in the structure pNewMsgFunc will point to the NewMsg() function.
But I could not get it how its possible without intialising tNewMsg with the address of
the NewMsg() function.But this code is running fine.There is no other constructors used to
intialise the function pointer with the address of the function NewMsg().
Event.cpp
#import "RsMsg.h"
#import "RsMsgDerived.h"
RsMsg* RsMsg::CreateMessage(REMOTE_MESSAGE_ID nMessageNumber)
{
RsMsg* pMsg = NULL;
stRsStruct* pMsgStruct;
pMsg = pMsgStruct->pNewMsgFunc(); //Invoking the function pointer
}
Here by invoking the function pointer I’m calling the static NewMsg() function.
But how this function gets called as pNewMsgFunc() is not assigned the address of NewMsg.
I need to call the NewMsg() function through pNewMsgFunc(). Is there any change to be made in the above code?
EDITED:
How to implement the same code in Objective C. This function pointer calls a function
whose return type is a class.So though the function pointers can be implemented in C as
its calling a function whose return type is a class cannot be implemented in Objective C
as c function.
No, it’s not.
tNewMsgis a name that identifies a type.…but
pNewMessageFuncis an object of that type.Look at it this way. In this code:
nis not an alias ofuint. Rather,nis a variable of typeuint.So,
pNewMessageFuncis a global variable (of type pointer-to-function-which-takes-no-parameters-and-returns-pointer-to-RsMsg) which you never initialize.