CRT terminators(VC)

CRT terminators(VC)

本文关键字:VC terminators CRT      更新时间:2023-10-16

我在"。CRT$XTU"节,但当应用程序退出时不调用该函数。

代码块1:

typedef int (__cdecl *_PVFV)();
static int __cdecl on_process_term()
{
    //do something
    return 0;
}
#pragma section(".CRT$XTU",long,read)
__declspec(allocate(".CRT$XTU"))_PVFV my_process_terminator= on_process_term;

我注册了on_process_term(),但是我的测试应用程序从未达到on_process_term()函数。

我跟踪了crt的源代码,发现这似乎是因为我的exe应用程序动态链接到crt的dll。

代码块2:

#ifndef CRTDLL
        /*
         * do terminators
         */
        _initterm(__xt_a, __xt_z);
#endif  /* CRTDLL */

代码块2中的代码可以在doexit()函数中找到,该函数由exit()函数调用。

宏CRTDLL被定义,因为我的exe是动态链接到crt dll(msvcr110.dll?),所以_initterm(__xt_a, __xt_z);这一行被"注释掉"。因此不会调用任何终止符。

代码块3:

/***
* __crtdll_callstaticterminators
*
*Purpose:
*       call terminators. This is called from CRT_INIT when dll entrypoint is
*       called with DLL_PROCESS_DETACH. We can't call the terminators from exit
*       as there may be some dll that may need crt functionality during
*       DLL_PROCESS_DETACH
*
*******************************************************************************/
void __crtdll_callstaticterminators(void) {
    /*
     * do pre-terminators
     */
    _initterm(__xp_a, __xp_z);
    /*
     * do terminators
     */
    _initterm(__xt_a, __xt_z);
}

__crtdll_callstaticterminators()将在CRT DLL从应用程序分离时调用,并执行终止程序。正如文档声明的那样,crt dll是动态链接到我的应用程序的,所以"代码块2"中的代码被"注释掉",并且这里将调用终止函数。但是,my on_process_term不能在"代码块3"中的__xt_a到__xt_z的终止符中找到。"代码块2"中的终止符似乎与"代码块3"中的终止符不一样。

有人能帮我解决这个问题吗?为什么不调用on_process_term ?怎么叫呢?

多谢!

调用它的解决方案是使用标准机制。特别是std::atexit。不管你如何连接CRT,效果都是一样的