提取 2 个类型转换为 (void*) 的指针
我试图传递 2 个指针作为另一个类型转换为 (void*) 的函数的争论 如何在最终函数中分离这两个?
例子:
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 = pLc;
_beginthread(Run,0,(void*)(m_pMsgQueue,m_pLc));
}
~Backgrounder(){ }
};
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 = pLc;
_beginthread(Run,0,(void*)(m_pMsgQueue,m_pLc));
}
~Backgrounder(){ }
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该创建一个以这两种指针类型作为成员的
struct
,并传递一个指向该结构的指针。You should create a
struct
with these two pointer types as members, and pass a pointer to that around.表达式
(m_pMsgQueue,m_pLc)
的作用与您想象的不同;它调用逗号运算符,该运算符仅计算第二个参数。将参数捆绑到一个结构中并传递它。
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.
您可以将它们包装在一个结构中,并传递一个指向该结构的指针。但要小心,因为该结构不应该在
Backgrounder
构造函数本地声明 - 这会导致未定义的行为,因为在启动它的函数之后线程可能仍在运行终止。它应该是动态分配的、静态类成员或全局变量。实际上,我会传递
this
指针,因为您本质上希望能够访问Run
函数中对象的字段:当然,您需要确保新创建的Backgrounder对象没有被提前销毁,即线程应该在销毁之前完成。
此外,如果稍后从父线程修改这些字段,您将需要采用适当的同步机制。
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, astatic
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 theRun
function: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.