0x26res
0x26res

Reputation: 13932

AfxGetInstanceHandle() triggers an assertion failure

I am using MFC in my C++ program (using Visual Studio 2008). I have to call AfxGetInstanceHandle() at the begining of my program.

This function triggers a break point:

AFXWIN_INLINE HINSTANCE AFXAPI AfxGetInstanceHandle()
{ ASSERT(afxCurrentInstanceHandle != NULL);
return afxCurrentInstanceHandle; }

The ASSERT statement fails. Is there something special that needs to be done in order to initialize the afxCurrentInstanceHandle before we try to access it?

PS: I am using MFC in a shared dll.

EDIT

My code is like that:

int _tmain(int argc, _TCHAR* argv[])
{

  CoInitialize(NULL);
  AfxGetInstanceHandle();
  return 0;
}

I would like to use the InstanceHandle in order to initialize a CComModule and then use it to manipulate com object.

Upvotes: 13

Views: 10018

Answers (4)

user2528794
user2528794

Reputation: 181

I made a Console App with MFC and got the Message too. I found the solution, that you need a "prologue" at the beginning of your main (_tmain, etc).

int main(int args, char* argv[]) //, char *envp[])
{
    // initialize MFC and print and error on failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))  
    {       
        // TODO: change error code to suit your needs       
        cerr << _T("Fatal Error: MFC initialization failed") << endl;       
        return 1;   
    }   
    AfxGetInstanceHandle();
    // TODO: code your application's behavior here.
    ...

Upvotes: 18

Vin.X
Vin.X

Reputation: 4849

Use:

AFX_MANAGE_STATE(AfxGetStaticModuleState());

Before you call:

AfxGetInstanceHandle();

Upvotes: 9

ymett
ymett

Reputation: 2454

If you are using MFC you shouldn't be providing a main, wmain, _tmain, or WinMain -- MFC provides its own entry point. Put initialisation code in InitInstance of your CWinApp derived class. If you don't have a CWinApp derived class you haven't created the project correctly -- use the Visual Studio Wizards for creating an MFC application.

Upvotes: 2

Erik
Erik

Reputation: 91300

This can happen if you mix unicode/mbcs or debug/release build modes for DLL/application.

Upvotes: 6

Related Questions