在vc6中編譯一個MFC程序時其中有段代碼在創建數據庫連接報錯。
其源碼如下:
其中聲明
_ConectPtr m_pConn,在函數中
HRESULT hr = m_pConn.CreateInstance(__uuidof(Connection)); //_T("ADODB.Connection"));
if(FAILED(hr))
{
return false;
}
后來在檢查,發現需要調用AfxOleInit()初始化組件即可解決。而我在文件中是加入了::CoInitialize(),但是在實際運行中該函數并沒有起到作用。
而在所宣言中,AfxOleInit包含了CoInitialize()。但是為啥AfxOleInit能解決數據連接的CreateInterface問題呢?觀察
AfxOleInit的源碼。
--------------------------------------------------------------------------------
BOOL AFXAPI AfxOleInit()
{
_AFX_THREAD_STATE* pState = AfxGetThreadState();
ASSERT(!pState->m_bNeedTerm); // calling it twice?
// Special case DLL context to assume that the calling app initializes OLE.
// For DLLs where this is not the case, those DLLs will need to initialize
// OLE for themselves via OleInitialize. This is done since MFC cannot provide
// automatic uninitialize for DLLs because it is not valid to shutdown OLE
// during a DLL_PROCESS_DETACH.
if (afxContextIsDLL)
{
pState->m_bNeedTerm = -1; // -1 is a special flag
return TRUE;
}
// first, initialize OLE
SCODE sc = ::OleInitialize(NULL); //該句子做初始化ole
if (FAILED(sc))
{
// warn about non-NULL success codes
TRACE1("Warning: OleInitialize returned scode = %s.\n",
AfxGetFullScodeString(sc));
goto InitFailed;
}
// termination required when OleInitialize does not fail
pState->m_bNeedTerm = TRUE;
// hook idle time and exit time for required OLE cleanup
CWinThread* pThread; pThread = AfxGetThread();
pThread->m_lpfnOleTermOrFreeLib = AfxOleTermOrFreeLib;
// allocate and initialize default message filter
if (pThread->m_pMessageFilter == NULL)
{
pThread->m_pMessageFilter = new COleMessageFilter;
ASSERT(AfxOleGetMessageFilter() != NULL);
AfxOleGetMessageFilter()->Register();
}
return TRUE;
InitFailed:
AfxOleTerm();
return FALSE;
}
可見,AfxOleInit()是封裝了OleInitialize()來初始化com組件;
查詢網上資料說:OleInitialize內部調用了CoInitialize 。在OleInitialize比ConInitialize多了以下支持:
Clipboard
Drag and drop
Object linking and embedding (OLE)
In-place activation
如果你不需要這些附加功能,就用CoInitialize或CoInitializeEx。
但是在本人程序中調用CoInitialize不行而AfxOleInit可以,難道OleInitialize中創建的所附幾個在ADO com控件上用到,但是在寫了一個控制臺上的ado程序,調用CoInitialize卻是可行的。其中細節和玄妙打個標記,容以后在研究吧,偷懶了,如果發現CoInitalize不行就用AfxOleInit吧。
0-----
汗顏:因為在app的InitInstance中的粗心末尾加了一句::UnCoInitialize(),造成coinitalize錯誤。實際上2個函數都可以初始化ado組件。mark。