Extracting 2 pointers typecasted into (void*)
I'm trying to pass 2 pointers as an arguement for another function typecasted into (void*) How do I seperate those two in the final function?
Example:
class Backgrounder{
public:
MESSAGE_QUEUE* m_pMsgQueue;
LockSection* m_pLc;
static void __cdecl Run( void* args){
MESSAGE_QUEUE* s_pMsgQueue = (MESSAGE_QUEUE*)args[0]; // doesn't work
LockSection* s_pLc = (LockSection*)args[1]; // doesn't work
}
Backgrounder(MESSAGE_QUEUE* pMsgQueue,LockSection* pLc) {
m_pMsgQueue = pMsgQueue;
m_pLc =开发者_StackOverflow社区 pLc;
_beginthread(Run,0,(void*)(m_pMsgQueue,m_pLc));
}
~Backgrounder(){ }
};
You should create a struct
with these two pointer types as members, and pass a pointer to that around.
The expression (m_pMsgQueue,m_pLc)
doesn't do what you think it does; it invokes the comma operator, which simply evaluates to the second argument.
Bundle the arguments into a struct and pass that.
You could wrap them together in a struct and pass a pointer to that struct. Be careful though, because that struct should not be declared locally to the Backgrounder
constructor - that would cause undefined behaviour because the thread may still be running after the function that started it has terminated. It should either be dynamically allocated, a static
class member, or a global variable.
Actually, I would pass the this
pointer since you essentially want to be able to access the fields of the object within the Run
function:
class Backgrounder{
public:
MESSAGE_QUEUE* m_pMsgQueue;
LockSection* m_pLc;
static void __cdecl Run (void *pThis) {
MESSAGE_QUEUE* s_pMsgQueue = ((Backgrounder *) pThis)->m_pMsgQueue;
LockSection* s_pLc = ((Backgrounder *) pThis)->m_pLc;
}
Backgrounder(MESSAGE_QUEUE* pMsgQueue,LockSection* pLc) {
m_pMsgQueue = pMsgQueue;
m_pLc = pLc;
_beginthread(Run, 0, (void *) this);
}
~Backgrounder(){ }
};
Of course, you'll need to make sure that the newly created Backgrounder
object is not prematurely destroyed, that is, the thread should be finished before the destruction.
Also, if these fields are later modified from the parent thread, you'll need to employ the appropriate synchronisation mechanisms.
精彩评论