简体   繁体   English

将Windows消息循环封装到DLL中

[英]Encapsulate Windows message loop into a DLL

I would like to have a DLL with window creation and management code in a way that the developer could just add a named main.h header and load the DLL to be able to instance a window. 我希望有一个带窗口创建和管理代码的DLL,开发人员可以只添加一个命名的main.h头并加载DLL以便能够实例化一个窗口。

#include "dllheader.h" 

void user_main();

main = user_main; // attach user main to the dll callback

int user_main() {
    Window *w = new Window();
}

on the DLL side the code should look like 在DLL端,代码应该是这样的

void (*main)() = NULL;

int WinMain(...) {
   if(main)
       main(); // call the user defined funcion
   while(!done) {
       if(messageWaiting()) {
           processMessage();
       }
   }

}

Why? 为什么? because I want to deploy a window wrapper and avoid to have the user writting the WinMain entry point. 因为我想部署一个窗口包装器,并避免让用户写入WinMain入口点。 But a DLL project have a DLL main and a win32 project that uses a DLL complaim if linker doesnt find a winMain entry point. 但DLL项目有一个DLL main和一个win32项目,如果链接器没有找到winMain入口点,则使用DLL抱怨。

Is there a know solution for this kind of arrange? 这种安排有没有明确的解决方案?

Every Win32 application must have an entry point (usally WinMain). 每个Win32应用程序都必须有一个入口点(通常是WinMain)。 So you can't put the entry point in the DLL, because it's not really part of the EXE. 因此,您不能将入口点放在DLL中,因为它实际上不是EXE的一部分。 However the entry point can be in a statically linked library. 但是,入口点可以位于静态链接库中。 When the static library gets linked, the entry point becomes part of the EXE. 当静态库被链接时,入口点成为EXE的一部分。

But my suggestion is to avoid all this complexity. 但我的建议是避免所有这些复杂性。 Just make the users of your DLL call something like this: 只需让你的DLL用户调用如下:

int WinMain( HINSTANCE hInstance, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow )
{
    return WrapperDllMain( hInstance, hPrev, lpCmdLine, nCmdShow, &user_main );
}

The code is simple and easy to write. 代码简单易写。 It's not much effort on the part of the DLL users. DLL用户并没有太多的努力。 You have total control over the message loop (and the entire process lifetime). 您可以完全控制消息循环(以及整个过程生命周期)。

You can't implement an application's WinMain() entry point inside a separate DLL. 您无法在单独的DLL中实现应用程序的WinMain()入口点。 The application must implement its own entry points, or else the linker will complain, as you have already discovered. 应用程序必须实现自己的入口点,否则链接器会抱怨,正如您已经发现的那样。 The application's entry point can call functions that are in the DLL, ie: 应用程序的入口点可以调用DLL中的函数,即:

--- app ---

#include "dllheader.h" 

int user_main()
{
  ...
}

int WinMain(...)
{
  return dll_main(&user_main);
}


--- dll ---

int dll_main(void (*user_main)())
{
  if(user_main)
    user_main(); // call the user defined funcion

  while(!done)
  {
    if(messageWaiting())
    {
      processMessage();
    }
  }
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM