c - 如何在C中执行DLL中的线程

标签 c windows dll

我创建了一个运行 3 个工作线程的 DLL,并且主线程处于循环中等待线程完成。线程已创建,但线程未执行。

我尝试在使用 CreateThread() 创建的函数内设置 MessageBox 函数,但该框没有出现。我也尝试过调试,并且 CreateThread() 的返回值是有效的,因此线程被创建。

BOOL WINAPI DllMain() {
   main();
   return 1;
}

int main() {
    HANDLE h1, h2, h3;

    h1 = CreateThread(first)...
    h2 = CreateThread(second)...
    h3 = CreateThread(third)...

   WaitForSingleObject(h3, INFINITE);
   return 1;
}

first() {
    MessageBoxA("print some stuff");
    return;
}

我已经包含了一些布局的伪代码。由于其敏感性,我无法提供真实的代码。然而,这就是正在发生的事情。我在另一个加载此 .DLL 的项目中使用 LoadLibrary。 DLL 被加载并执行 DllMain。然后它调用我的 main 函数,它创建了 3 个线程。每个线程都被创建。但线程内部的内容不会执行。

编辑:

// dllmain.cpp : Defines the entry point for the DLL application.
#include <Windows.h>

void mb() {
    MessageBoxW(0, L"AAAAAAAAAAAAAAAAAAAAAAAAA", L"AAAAAAAAAAAAAAAAAAAAAAa", 1);
}

void create() {
    HANDLE han;
    DWORD threadId;
    han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);
    han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);
    han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);

}

BOOL APIENTRY DllMain() {
    create();
    return 1;
}

最佳答案

[MS.Docs]: DllMain entry point (强调是我的)指出:

Calling functions that require DLLs other than Kernel32.dll may result in problems that are difficult to diagnose. For example, calling User, Shell, and COM functions can cause access violation errors, because some functions load other system components. Conversely, calling functions such as these during termination can cause access violation errors because the corresponding component may already have been unloaded or uninitialized.

[MS.Docs]: MessageBox function驻留在User32.dll中,因此它是未定义行为(意味着在不同的场景下,它可能会起作用,它可能会出现故障,或者可能会崩溃)。

此外,正如 @RbMm 所注意到的,WaitForSingleObject 不属于那里。我也不确定 CreateThread(但我找不到任何官方文档来确认/确认它)。

出于好奇,您可以在 main 中添加一个 printf("main called.\n"); 来看看它被调用了多少次吗?

关于c - 如何在C中执行DLL中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54132232/

相关文章:

c - fork 后的 Unix dup 管道

c++ - win7 64 位上的正则表达式构建错误

javascript - 安装 gdal 以与 topo json 和 D3 一起使用

.net - .NET 程序集上的 AppLocker DLL 规则

C# Assembly.LoadFrom(myNetworkPath) 抛出 FileLoadException

c# - azure webjob找不到dll

c - 在键盘输入时无限循环停止时执行 - C

c++ - 如何在c或c++中通过鼠标左键拖动图形矩形

c - 这些 fork() 语句的进程树是什么样子的?

ruby - 包括鞋中鞋套餐