Click here to Skip to main content
15,890,043 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a MFC SDI GUI application in which I have a CMyApp member variable set at start-up which requires a COM interface.

So, in CMyApp::InitInstance() I have called:
CoInitializeEx(NULL, COINIT_MULTITHREADED);

However, when I shut down the app it crashes.

If I use
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED) 
it is fine.

Can anyone please tell me what the problem is? I have used
CoInitializeEx(NULL, COINIT_MULTITHREADED)
elsewhere in the application, e.g. in MyDoc.cpp and it does not cause any problem. I am not using multiple threads so I do not need to use the MULTITHREADED version, but i don't understand why it is causing the crash at shutdown (when it is trying to release an m_pInterace in the depths of microsoft's code).


Also, is CMyApp::InitInstance() the best place to initialise a member variable for the GUI that is not related to a document that is viewed. It stores an XMLDOMDocPtr to a file that contains a file path to some information that is used behind the GUI.

Many thanks.
Posted
Updated 21-Sep-11 0:13am
v2

1 solution

The first thing to do would be to check what the call returns. You can find more details here[^] but the simple explanation is: you should only call CoUninitialise if your call to CoInitialize SUCCEEDED:
"To close the COM library gracefully on a thread, each successful call to CoInitialize or CoInitializeEx, including any call that returns S_FALSE, must be balanced by a corresponding call to CoUninitialize."

My guess would be that the XMLDOMDocPtr calls CoInitialize with the APARTMENTTHREADED model and you get a RPC_E_CHANGED_MODE from your call. If this is the case you should not call CoUninitialize.
 
Share this answer
 
Comments
Jackie Lloyd 22-Sep-11 2:46am    
Thanks for that. Yeah, I have checked the HRESULT value that it returns, and it is S_OK, so there's nothing wrong with the call to CoInitializeEx. I also tried doing CoUninitialize staright after CoInitialize, and it still crashed later when the app was closed.

Well, at least it works now even if I am not sure why!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900