Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 925
0x26res Avatar asked Mar 02 '11 08:03

0x26res


2 Answers

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.
    ...
like image 112
user2528794 Avatar answered Oct 02 '22 04:10

user2528794


Use:

AFX_MANAGE_STATE(AfxGetStaticModuleState());

Before you call:

AfxGetInstanceHandle();
like image 22
Vin.X Avatar answered Oct 02 '22 05:10

Vin.X