Calling a method from a non-member method
Hi, I need to call a method from a non-member function. Is there a way to reach an object from the outside? (i'm sorry that i can't find the right way to express my question, but please bear with me...) I'm loking for something like
Appname->object.processMessage()
but I can't find a way to do it.
This is a stub of my class implementation.
I'm working with a subclass of QThread and HLP_Init comes from an external library. I tried to pass the method directly to the HLP Init, but that did not work because the compiler complained that the type of function was not right.
Code:
void HLPReceiveMessage(tyHLP_Message message, tyHLP_LinkID linkId)
{
//i need to call void HLP_LinkManager::processMessage() here
}
void HLPReceiveError(tyHLP_Error err, tyHLP_LinkID linkId)
{
}
void HLP_LinkManager::run()
{
int rc;
//HLP server initialization
rc=HLP_Init(HLP_LINK_SERVER,HLPReceiveMessage,HLPReceiveError);
}
void HLP_LinkManager::processMessage()
{
//do stuff here
}
And thanks in advance!
Re: Calling a method from a non-member method
Just add a parameter to the functions, of type HLP_LinkManager*.
Code:
void HLP_LinkManager::run()
{
int rc;
//HLP server initialization
rc=HLP_Init(HLP_LINK_SERVER,HLPReceiveMessage,HLPReceiveError,this);
}
void HLPReceiveMessage(tyHLP_Message message, tyHLP_LinkID linkId,HLP_LinkManager* pHlpMgr)
{
pHlpMgr->processMessage();
}
Re: Calling a method from a non-member method
The problem is that I can't alter the HLP_Init nor the RecieveMessage declarations. That is why i'm trying to acess from a global variable.
In any case, taking into account your idea, i've been thinking in whether i can wrap those functions, but i can't get to anything that works.
Re: Calling a method from a non-member method
You need an instance of HLP_LinkManager to be able to call non-static member methods. If you cannot provide an instance then you cannot access these methods.
Re: Calling a method from a non-member method
in that case, the only option I see is using a global:
Code:
HLP_LinkManager *g_pLinkMgr = NULL;
void HLPReceiveMessage(tyHLP_Message message, tyHLP_LinkID linkId)
{
//i need to call void HLP_LinkManager::processMessage() here
if(g_pLinkMgr){
g_pLinkMgr->processMessage();
}
}
void HLP_LinkManager::run()
{
int rc;
g_pLinkMgr = this;
//HLP server initialization
rc=HLP_Init(HLP_LINK_SERVER,HLPReceiveMessage,HLPReceiveError);
}
Re: Calling a method from a non-member method
Thanks, the code that you provided is better than mine, i did not thought about leaving the global as null and then using "this", but now this way solves my problem