2011-03-02 156 views
9

我在我的C++程序(使用Visual Studio 2008)中使用MFC。我必須在我的程序開始時調用AfxGetInstanceHandle()。AfxGetInstanceHandle()觸發斷言失敗

該功能會觸發一個破發點:

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

斷言語句失敗。我想知道在我們嘗試訪問它之前,您是否需要執行以初始化afxCurrentInstanceHandle

PS:我在共享的DLL中使用MFC。

編輯

我的代碼是這樣的:

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

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

我想,以初始化CComModule,然後用它來操縱COM對象使用InstanceHandle

回答

2

如果您正在使用MFC你不應該提供主,wmain,_tmain,或WinMain函數 - MFC提供了自己的切入點。將初始化代碼放入CWinApp派生類的InitInstance中。如果您沒有CWinApp派生類,您尚未正確創建項目 - 請使用Visual Studio嚮導創建MFC應用程序。

+0

因此,如果沒有全部的CWinApp對象,就沒有辦法訪問AfxGetInstanceHandle() – Arthur 2011-03-02 12:52:40

+0

我覺得我做錯了什麼,而我並不真的需要使用COM對象。謝謝。 – Arthur 2011-03-03 15:56:54

+2

Downvote,因爲這是不正確的。對於Window/GUI應用程序,您的聲明是正確的,項目wizzard將創建一個CWinApp派生類。但是,當您使用MFC支持創建控制檯應用程序時,將創建帶有main(_tmain)函數的源代碼,並首先調用AfxWinInit來設置MFC。 – 2013-06-28 11:48:50

5

,如果你對DLL /應用混合的Unicode/MBCS或調試/發佈構建模式會發生這種情況。

+0

我的項目和它的所有依賴關係正在使用MFC在一個共享的DLL,使用MultiThreaded Debug DLL和使用多字節字符。這可能是由於別的東西 – Arthur 2011-03-02 09:03:03

+0

這解決了我的問題。 – 2011-07-28 19:31:16

6

用途:

AFX_MANAGE_STATE(AfxGetStaticModuleState()); 

在打電話:

AfxGetInstanceHandle(); 
7

我做了一個控制檯應用程序與MFC和得到的消息了。我找到了解決方案,你需要在主要(_tmain等)開頭的「序言」。

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