【问题标题】:__attribute__((destructor)) equivalent in VC?VC 中的 __attribute__((destructor)) 等价物?
【发布时间】:2013-12-21 23:30:30
【问题描述】:

我查看了__attribute__((constructor)) equivalent in VC?CRT Initialization,它们都对gcc 特定的__attribute__((constructor)) 很有帮助。但是__attribute__((destructor)) 呢?有 VC 等价物吗?

【问题讨论】:

  • 您链接的答案提供了等效的功能,使用 atexit 请参阅msdn.microsoft.com/en-us/library/tze57ck3.aspx
  • 如果是库 - 在DllMain 中您可以安全地做的很少(阅读:调用 Kernel32.dll 的函数,只要它们不加载库 - 几乎没有别的)。不幸的是,其他方法(atexit 等)也好不了多少,因为它们往往是通过DllMain 实现的。在这种情况下,重写代码往往是一种简单的选择。

标签: c++ c visual-c++


【解决方案1】:

如果你正在制作一个动态链接库,你可以让你的DllMain entry point 处理这个:

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    if (fdwReason == DLL_PROCESS_ATTACH)
    {
        // equivalent of __attribute__((constructor))...

        // return TRUE if succeeded, FALSE if you failed to initialize properly
        return TRUE; // I'm assuming you succeeded.
    }
    else if (fdwReason == DLL_PROCESS_DETACH)
    {
        // equivalent of __attribute__((destructor))...
    }

    // Return value is ignored when fdwReason isn't DLL_PROCESS_ATTACH, so we'll
    // just return TRUE.
    return TRUE;
}

【讨论】:

  • 有趣,实际上似乎比 gcc 的 __attribute__ 更清晰。我会留意有关DllMain 的警告,看看我能做什么。谢谢!
猜你喜欢
  • 2020-05-29
  • 1970-01-01
  • 2016-02-13
  • 1970-01-01
  • 2014-10-26
  • 1970-01-01
  • 2012-12-28
  • 2011-04-30
相关资源
最近更新 更多