Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3291351
  • 博文数量: 754
  • 博客积分: 10132
  • 博客等级: 上将
  • 技术积分: 7780
  • 用 户 组: 普通用户
  • 注册时间: 2008-01-14 23:36
文章分类

全部博文(754)

文章存档

2012年(3)

2011年(39)

2010年(66)

2009年(167)

2008年(479)

我的朋友

分类: WINDOWS

2008-02-22 10:02:53

在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。

阅读(1415) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~