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.
DECLARE_NEWMSG? Also, the title means almost nothing.RsMsg::CreateMessageas you wrote it will almost certainly segfault. The pointerpMsgStructis not initialized, so it could be pointing anywhere in memory. ThenpMsgStruct->pNewMsgFunc()will load whatever random address is at that memory location and try to start executing code there. You should post more of the real code so that people can see what is happening.stRsStruct.