Click here to Skip to main content
13,256,841 members (51,246 online)
Click here to Skip to main content
Add your own
alternative version


21 bookmarked
Posted 20 Jan 2003

AtInitExitInstance - Register functions to be called during InitInstance and ExitInstance

, 20 Jan 2003
Rate this:
Please Sign up or sign in to vote.
A technique to register functions to be called during InitInstance and ExitInstance


If you want to initialize some variables before the main code has executed, using standard C/C++ you can create a static initializer like this:

int myVar = 0x1234;

int main(void)
    return myVar;

If you want to run some code, you can create a class and use a static constructor to accomplish it.

class Init
    Init() { printf(_T("Hello World")); }

static Init _init;

int main(void)
    return 0;

Also, if you want to execute some code after main has exited you can use atexit

void *pMemory;

void deleteMemory(void)
    delete pMemory;

int main(void)

    pMemory = new char[100];

    return 0;

So, after main has exited, deleteMemory will be called before the process has been shut down

Now, all of this is OK for most cases, but recently I've been writing a large project that has multiple DLLs, using several plugins, loads of databases and good helpings of OLE.

Anyone who has used CRecordset in DLLs, will tell you that if you want to have a statically created CRecordset then you need to create it dynamically.

CMyRecordset staticSet;
CMyOtherRecordset *pDynamicSet;

If this code is in a DLL, then the first instance, will be created during DLL startup, and if the record-set is still in use during shutdown, you will get an exception thrown, because the database is trying to close itself, but some of the database machinery has probably been already closed down.

For the second instance, you will need to create the database during DLL startup manually, BUT you can't do it in DllMain because things might not be up and running when it is called, and also, you are limited to what you can actually call during this function.

What we need is to be able to call this function later.

Also, we need to be able to close and delete the record-set later, but before DllMain is called with the shutdown parameters.

The solution

It is for this purpose that I wrote the following functions :

typedef void (*AtExitInstanceFunc_t)(void);

CList<AtExitInstanceFunc_t, AtExitInstanceFunc_t>p_AtExitInstanceFuncList;

void AtExitInstance(void (*func)(void))
    p_AtExitInstanceFuncList.AddTail (func);

void AtExitInstanceExecute()
    while(p_AtExitInstanceFuncList.GetCount ())
        AtExitInstanceFunc_t func = p_AtExitInstanceFuncList.RemoveHead ();

typedef void (*AtInitInstanceFunc_t)(void);

CList<AtInitInstanceFunc_t, AtInitInstanceFunc_t>p_AtInitInstanceFuncList;

void AtInitInstance(void (*func)(void))
    p_AtInitInstanceFuncList.AddTail (func);

void AtInitInstanceExecute()
    while(p_AtInitInstanceFuncList.GetCount ())
        AtInitInstanceFunc_t func = p_AtInitInstanceFuncList.RemoveHead ();

The downloadable source contains a MFC Extension DLL project that just contains these functions (with headers). The Release DLL is only 24kb, so it won't take up too much room on your disk :-). It only contains a .dsp file, as it is designed to be used as it within a bigger project, so you just include it in your current project.

Basically, all that happens is you register a function to be called later, and If you need to run a function nearer the start of program execution, do something like:

#include <InitExit.h>

CMyOtherRecordset *pDynamicSet;

void deleteSet(void)
    delete pDynamicSet;

void initialiseSet(void)
    pDynamicSet = new CMyOtherRecordset;


extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
    // Remove this if you use lpReserved

    if (dwReason == DLL_PROCESS_ATTACH)
        TRACE0("SMARTMERGE.DLL Initializing!\n");
        // Extension DLL one-time initialization
        if (!AfxInitExtensionModule(SmartMergeDLL, hInstance))
            return 0;

        new CDynLinkLibrary(SmartMergeDLL);


    else if (dwReason == DLL_PROCESS_DETACH)
        TRACE0("SMARTMERGE.DLL Terminating!\n");
        // Terminate the library before destructors are called
    return 1; // ok

This code will, during startup, queue initialiseSet to be executed later. When initialiseSet has been executed, deleteSet will be queued for execution on program shutdown.

All that's left to do is to add some code to the InitInstance/ExitInstance functions of the .EXE :

#include <InitExit.h>

BOOL CFailsworthApp::InitInstance()
    CWaitCursor cur;

    if (!AfxSocketInit())
        return FALSE;
    // Initialize OLE libraries
    if (!AfxOleInit())
        return FALSE;
    // Standard initialization
    // If you are not using these features and wish to reduce the size
    //  of your final executable, you should remove from the following
    //  the specific initialization routines you do not need.
#ifdef _AFXDLL
    Enable3dControls(); // Call this when using MFC in a shared DLL
    Enable3dControlsStatic(); // Call this when linking to MFC statically

    // Parse command line for standard shell commands, DDE, file open
    CCommandLineInfo cmdInfo;
    // Dispatch commands specified on the command line
    if (!ProcessShellCommand(cmdInfo))
        return FALSE;
    // The main window has been initialized, so show and update it.
    return TRUE;

int CFailsworthApp::ExitInstance() 

    return CWinApp::ExitInstance();

I've added these calls after the majority of the initialization has taken place, but before the main window is shown. This allows as much of the machinery to be startup up as possible, before I try and actually use it.

The prototype for both types of functions are void func(void); so no parameters are passed and no return value is required.


You can also specify a function to be called using #pragma init_seg, but the ordering of calls is not really known.


Although standard C/C++ will give a version of this startup/shutdown process, sadly this doesn't work under all (windows) cases. The solution I have provided certainly works, and provides centralized routines to accomplish the goal under these special cases.

Thanks for reading. Hello mum!


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Web Developer
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralSingleton class Pin
Cool#94-Feb-03 1:53
memberCool#94-Feb-03 1:53 
GeneralRe: Singleton class Pin
soundman324-Feb-03 2:05
membersoundman324-Feb-03 2:05 
GeneralNice concept & implementation Pin
Eric Anderton22-Jan-03 9:08
memberEric Anderton22-Jan-03 9:08 
GeneralMemory Leak Pin
Victor Boctor21-Jan-03 18:38
memberVictor Boctor21-Jan-03 18:38 
GeneralRe: Memory Leak Pin
Jörgen Sigvardsson22-Jan-03 12:11
memberJörgen Sigvardsson22-Jan-03 12:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171114.1 | Last Updated 21 Jan 2003
Article Copyright 2003 by soundman32
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid