带createthread和printf的DllMain

时间:2018-07-27 16:39:49

标签: c++ winapi

我正在尝试使用mingw-64构建Windows dll,一旦加载,它将开始无限期地打印“ Hello World”。

这是我的dll.c

#ifndef DLL_H_
#define DLL_H_

#ifdef BUILD_DLL
/* DLL export */
#define EXPORT __declspec(dllexport)
#else
/* EXE import */
#define EXPORT __declspec(dllimport)
#endif

#endif /* DLL_H_ */

这是我的dll.h:

#include <windows.h>
#include <iostream>

typedef int (__stdcall *f_funci)();

int main()
{
  HINSTANCE hGetProcIDDLL = LoadLibrary("./wow.dll");

  if (!hGetProcIDDLL) {
    std::cout << "could not load the dynamic library" << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

所以我建立了一个简单的程序来加载我的DLL,以查看它是否正常工作,这里是:hello.cpp

multiprocessing

现在,当我将hello.cpp编译为hello.exe并将dll.c编译为wow.dll时,控制台上什么也没有。怎么了?

2 个答案:

答案 0 :(得分:0)

首先,我想提一下,不建议在线程中实现这种繁忙的循环。

关于您遇到的问题,这里有几个潜在问题:

  1. printf是CRT函数,但是您正在调用CreateThread()而不是beginthread(ex),因此CRT没有正确初始化。
  2. DLL入口点是一个臭名昭著的地方。您几乎无法从那里调用任何kernel32函数,更不用说CRT了(请参见DllMain entry pointDynamic Link Library Best Practices)。

在大多数情况下,建议实现单独的InitExit函数,客户端在使用您的库时需要调用这些函数。

答案 1 :(得分:0)

如上所述,您的mainThread函数签名错误。尝试这样的事情:

DWORD WINAPI mainThread(LPVOID lpParam)
{
    UNREFERENCED_PARAMETER(lpParam);
    while (1)
    {
        printf("Hello world!\n");
        Sleep(1000);
    }
    return 0;
}

这对我来说很好。我修改了您的.exe,以便您可以将.dll拖放到其上进行测试:

#include <windows.h>
#include <iostream>

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        std::cout << "drag drop dll over exe" << std::endl;
        std::cin.get();
        return EXIT_FAILURE;
    }

    HINSTANCE hGetProcIDDLL = LoadLibraryA(argv[1]);

    if (!hGetProcIDDLL)
    {
        std::cout << "could not load the dynamic library" << std::endl;
        std::cin.get();
        return EXIT_FAILURE;
    }

    std::cin.get();
    return EXIT_SUCCESS;
}