开发者

AfxGetInstanceHandle() triggers an assertion failure

开发者 https://www.devze.com 2023-02-14 02:38 出处:网络
I am using MFC in my C++ program (using Visual Studio 2008). I have to call AfxGetInstanceHandle() at the begining of my program.

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 i开发者_开发技巧t to manipulate com object.


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.
    ...


Use:

AFX_MANAGE_STATE(AfxGetStaticModuleState());

Before you call:

AfxGetInstanceHandle();


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消