Note that there are some explanatory texts on larger screens.

plurals
  1. POFunction pointers in Objective C
    primarykey
    data
    text
    <p>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.</p> <p>Here <code>pNewMsgeFunc</code> is the alias name of the function pointer <code>tNewMsg</code> which is created inside the structure <code>stRsStruct</code>.</p> <p>RsMsg.h</p> <pre><code>typedef RsMsg* (*tNewMsg)(void); tNewMsg pNewMsgFunc; typedef struct { int nMsgId; NSString* sAsciiName; tNewMsg pNewMsgFunc; // calls new for the particular message } stRsStruct; </code></pre> <p>RsMsg.cpp</p> <pre><code>RsMsg(int uMessageId,tNewMsg pNewMsg,const char* szAsciiName,void* pData, size_t uDataSize) { //intialisations } </code></pre> <p>RsMsgDerived.h</p> <pre><code>#define DECLARE_NEWMSG(CssName,CssID) \ static CssName* FromMsg(RsMsg* pMsg) \ { \ return dynamic_cast&lt;CssName*&gt;(pMsg); \ } \ static RsMsg* NewMsg() \ { \ return new CssName; \ } \ enum {ID = CssID}; \ </code></pre> <p>Its said that in the structure pNewMsgFunc will point to the NewMsg() function.</p> <p>But I could not get it how its possible without intialising tNewMsg with the address of </p> <p>the NewMsg() function.But this code is running fine.There is no other constructors used to </p> <p>intialise the function pointer with the address of the function NewMsg().</p> <p>Event.cpp</p> <pre><code>#import "RsMsg.h" #import "RsMsgDerived.h" RsMsg* RsMsg::CreateMessage(REMOTE_MESSAGE_ID nMessageNumber) { RsMsg* pMsg = NULL; stRsStruct* pMsgStruct; pMsg = pMsgStruct-&gt;pNewMsgFunc(); //Invoking the function pointer } </code></pre> <p>Here by invoking the function pointer I'm calling the static <code>NewMsg()</code> function.</p> <p>But how this function gets called as <code>pNewMsgFunc()</code> is not assigned the address of <code>NewMsg</code>.</p> <p>I need to call the <code>NewMsg()</code> function through <code>pNewMsgFunc()</code>. Is there any change to be made in the above code?</p> <p>EDITED:</p> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload