By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,039 Members | 1,824 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,039 IT Pros & Developers. It's quick & easy.

How to Update a Object within a Callback Function

P: 1
Hi,

I have a problem of how to update the Object data of a Class from within a Callback function that is not a member function of that Class, its just a C function.


void CallBack( int reason, Snmp *snmp, Pdu &pdu, SnmpTarget &target, void *cd) // just a C function not a member function

{

// can i update the contents of the Object
// or the flow be passed to one of the member functions


}

Class A {

private:
/* data members */
public:
void example ( );
void example1 ( );

}

void A::example ()
{
/******

status = snmp.notify_register(oidc, targetc, CallBack, NULL);


}

In the above dummy coding very similar to my actuall requirement i call back function "CallBack" is called by snmp.notify_register.

Can i update the private data members of the Class or can i sent the control back to one of the member functions of that Class with the all the data members updated.

Thanks in Advance

Regards
SAK
Aug 7 '07 #1
Share this Question
Share on Google+
2 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
Can i update the private data members of the Class...
Yes. Provided your function is a friend of the class.

Otherwise, you will need to use the public member functions like eveyone else.

Friend functions are discouraged and should only be used when the member function cannot have a this pointer as the first argument. Any other uses, generally, are there to bypass those messy rules about preserving encapsulation.
Aug 7 '07 #2

RRick
Expert 100+
P: 463
Callbacks between C APIs and C++ objects are possble without friend declarations. A typical C callback mechanism allows you to define/register a C style callback function with a void * data.

In this case, you register a static method from the object and pass the object as the void * data. When the callback is used, the C routine also passes back your object as the void * data. I assume that is what the last parameter is about. (If not, then oh-well, it was a nice idea).

Let's look at an example:

Expand|Select|Wrap|Line Numbers
  1. class CallMe
  2. {
  3. ......
  4. static void CallBack( int reason, Snmp *snmp, Pdu &pdu, SnmpTarget &target, void *cd)
  5. };
  6.  
When CallMe::CallBack is compiled you will have access to all the static data in CallMe and access to a specific CallMe object. I believe you can access private data in the CallMe object from the static method.
Aug 8 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.