为什么这个C程序无限循环?

时间:2013-10-20 00:26:05

标签: c winapi dll

我写了一个DLL文件,我可以将其注入另一个进程。一旦注入,它应该创建一个消息框。它似乎创建了无数的消息框和我的计算机崩溃。有任何想法吗?另外,DLLIMPORT和DWORD WINAPI有什么区别?主要应该是DLLIMPORT还是其他?

dllmain.c

/* Replace "dll.h" with the name of your header */
#include "dll.h"
#include <windows.h>

DLLIMPORT void HelloWorld() {
    MessageBox(0,"Hello World from DLL!\n","Hi",MB_ICONINFORMATION);
}

int main() {
    MessageBox(0,"Hello World from DLL!\n","Hi",MB_ICONINFORMATION);
}

DWORD WINAPI Main(LPVOID lpParam) {
    main();
    return S_OK;
}

BOOL WINAPI DllMain(
    HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
    switch(fdwReason) {
        case DLL_PROCESS_ATTACH:
        break;

        case DLL_PROCESS_DETACH:
        break;

        case DLL_THREAD_ATTACH:
        DisableThreadLibraryCalls(hinstDLL);
        CreateThread(NULL, 0, &Main, NULL, 0, NULL);
        break;

        case DLL_THREAD_DETACH:
        break;
    }

    return TRUE;
}

dll.h

#ifndef _DLL_H_
#define _DLL_H_

#if BUILDING_DLL
#define DLLIMPORT __declspec(dllexport)
#else
#define DLLIMPORT __declspec(dllimport)
#endif

DLLIMPORT void HelloWorld();

#endif

1 个答案:

答案 0 :(得分:2)

当DLL附加到进程而不是线程时执行线程:

...
        case DLL_PROCESS_ATTACH:
        DisableThreadLibraryCalls(hinstDLL);
        CreateThread(NULL, 0, Main, NULL, 0, NULL);
        break;

        case DLL_PROCESS_DETACH:
        break;

        case DLL_THREAD_ATTACH:
        break;

        case DLL_THREAD_DETACH:
        break;
...

并检查您传递给CreateThread的回调,它应该是Main而不是&Main,它已经是指针。