gpt4 book ai didi

c++ - ShellExecute 在_beginthread

转载 作者:行者123 更新时间:2023-11-27 23:57:12 24 4
gpt4 key购买 nike

例如我需要运行:

ShellExecute(NULL, "open", "program.exe", NULL, NULL, SW_HIDE);

作为新线程,但我不知道如何。我试过这个:

HANDLE hThread = (HANDLE) _beginthread(ShellExecute(NULL, "open", "program.exe", NULL, NULL, SW_HIDE), 0, NULL);
WaitForSingleObject( hThread, INFINITE );

但显然是错误的,无法编译。我应该怎么做?

最佳答案

你的尝试确实明显是错误的,但问题是你是否理解它的错误所在。 _beginthread指向函数的指针(具有特定原型(prototype)和调用约定)作为其第一个参数。

当你写作时

HANDLE hThread = (HANDLE) _beginthread(ShellExecute(NULL, "open", "program.exe", NULL, NULL, SW_HIDE), 0, NULL);

您正在尝试将调用 ShellExecute(在当前线程中)的结果传递给 _beginthread,这是一个HINSTANCE,而 _beginthread 期望一个 void( __cdecl *)( void * )(指向一个 __cdecl 函数的指针,它采用一个 void * 参数并返回 void).

不仅你的代码不起作用,因为你试图传递一个 HINSTANCE ,其中一个函数指向指针,它没有任何意义。你读过_beginthread documentation吗? ?那里有例子。复数。

你想写的是:

HANDLE hThread = (HANDLE) _beginthread(ThreadFunc, 0, NULL);

给出:

void __cdecl ThreadFunc(void*) {
ShellExecute(NULL, "open", "program.exe", NULL, NULL, SW_HIDE);
}

或者,以更紧凑和易于阅读的形式:

HANDLE hThread = (HANDLE)
_beginthread([](void*) {
ShellExecute(NULL, "open", "program.exe", NULL, NULL, SW_HIDE);
},
0, NULL);

除非你正在做一些超出我们在这里看到的事情,否则大卫的评论可能是正确的,你应该使用 std::threadstd::async.

还请注意,将 _beginthread 的结果(与 _beginthreadexCreateThread 的结果进行对比)是不安全的,因为它可能不安全有效,如文档中所述。不仅如此,_beginthread 的返回值并不是真正的HANDLE(它有点像句柄,但不是HANDLE !), 所以你不能在上面 WaitForSingleObject:

The _beginthreadex function gives you more control over how the thread is created than _beginthread does. The _endthreadex function is also more flexible. For example, with _beginthreadex, you can use security information, set the initial state of the thread (running or suspended), and get the thread identifier of the newly created thread. You can also use the thread handle that's returned by _beginthreadex with the synchronization APIs, which you cannot do with _beginthread.

It's safer to use _beginthreadex than _beginthread. If the thread that's generated by _beginthread exits quickly, the handle that's returned to the caller of _beginthread might be invalid or point to another thread. However, the handle that's returned by _beginthreadex has to be closed by the caller of _beginthreadex, so it is guaranteed to be a valid handle if _beginthreadex did not return an error.

由于这个线程只调用一个函数就退出了,几乎最大化了这个句柄无效的几率。即使是,您仍然不能将它用于 WaitForSingleObject

关于c++ - ShellExecute 在_beginthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41723033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com