您的位置:首页 > 编程语言

main函数之前执行代码

2011-12-31 23:08 666 查看
有的时候,需要会遇到这样的一个情况,“想要在main或者WinMain函数执行前初始化我们的系统框架,和在之后释放我们的系统框架”, 如果这样,我们该怎么做呢?笔者今天放假,来公司继续解决昨天剩余的问题,然后调试exit函数的时候,会发现它会调用
static void __cdecl doexit (int code, int quick,int retcaller)这样的一个内部函数,那么继续单步调试,那么你就会发现

/* from the CRT */
typedef void (*_PVFV)(void);
void _initterm(_PVFV *begin, _PVFV *end)
{
   _PVFV *cur;
   for (cur = begin; cur < end; cur++)
   {
      /* skip NULL pointers */
      if (*cur)
      {
         (**cur)();
      }
   }
}


很容易就可以看到,他就是一个循环遍历,执行每个元素,而仔细看看,那每个元素不就是一个函数指针吗? OK,我们想实现前面所说的功能,该怎么做呢?怎么能够自动往里面添加我们的函数指针呢? 如果能够自由添加我们的函数指针的话,就可以在main和WinMain之前,之后分别调用我们自己的 “初始化”“退出”函数了。那么我们继续在这个源文件中“crt0dat.c”中看看其他代码,或许你会幸运的发现如下代码:

......................................

#pragma section(".CRTMP$XCA",long,read)
#pragma section(".CRTMP$XCZ",long,read)
#pragma section(".CRTMP$XIA",long,read)
#pragma section(".CRTMP$XIZ",long,read)

......................................

#define _CRTALLOC(x) __declspec(allocate(x))


OK,得到上述的那些信息,我们可以开始尝试了,输入以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

class A
{
public:
A()
{
printf("A()\n");
}
~A()
{
printf("~A()\n");
}
};

A a;

bool b = false;
int foo()
{
if (!b)
{
printf("init now!\n");
b = true;
}
else
{
printf("uninit now\n");
}
return 0;
}

typedef int (__cdecl *_PVFV)();
#pragma section(".CRT$XIU", long, read)
#pragma section(".CRT$XPU", long, read)
__declspec(allocate(".CRT$XIU")) _PVFV mgt_startup[] = { foo };
__declspec(allocate(".CRT$XPU")) _PVFV mgt_exit[] = { foo };

int main()
{
printf("main.!\n");
//exit(1);
return 0;
}


那么,你可以Ctrl+F5测试一下, 你可以看到 init A() main() ~A() uninit 这样的顺序,呵呵,总之目标实现啦,其实原理也很简单的,我就不讲啦, 杭州天气太热了。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: