WEB开发网
开发学院软件开发VC 理解 COM 套间 阅读

理解 COM 套间

 2006-07-22 22:58:03 来源:WEB开发网   
核心提示: #define _WIN32_WINNT 0x0400#include <windows.h>#include <iostream>#include "..\TestComObject1\TestComObject1_i.c"#include &

#define _WIN32_WINNT 0x0400
  #include <windows.h>
  #include <iostream>
  
  #include "..\TestComObject1\TestComObject1_i.c"
  #include "..\TestComObject1\TestComObject1.h"
  
  DWORD WINAPI ThreadProc(LPVOID lpv)
  {
  
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  
    if ( FAILED(hr) )
    {
      std::cout << "CoinitializeEx failed!" << std::endl;
      return 0;
    }
  
    ITestInterface1 *pTest = NULL;
  
    hr = ::CoCreateInstance(CLSID_TestInterface1,
        0,
        CLSCTX_INPROC,
        IID_ITestInterface1,
        (void**)&pTest);
  
    if ( FAILED(hr) )
    {
      std::cout << "CoCreateInstance failed!" << std::endl;
      return 0;
    }
  
    hr = pTest->TestFunc1();
  
    if ( FAILED(hr) )
    {
      std::cout << "TestFunc1 failed!" << std::endl;
      return 0;
    }
    
    pTest->Release();
    ::CoUninitialize();
    return 0;
  }
  
  int main(int argc, char* argv[])
  {
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  
    if ( FAILED(hr) )
    {
      std::cout << "CoinitializeEx failed!" << std::endl;
      return 0;
    }
  
    ITestInterface1 *pTest = NULL;
  
    hr = ::CoCreateInstance(CLSID_TestInterface1,
        0,
        CLSCTX_INPROC,
        IID_ITestInterface1,
        (void**)&pTest);
  
    if ( FAILED(hr) )
    {
      std::cout << "CoCreateInstance failed!" << std::endl;
      return 0;
    }
    
    DWORD threadID;
    HANDLE hThreads =  ::CreateThread(NULL, //创建一个进程
      0,
      ThreadProc,
      NULL, //将pTest作为一个参数传入新线程
      0,
      &threadID);
    hr = pTest->TestFunc1();
    
    if ( FAILED(hr) )
    {
      std::cout << "TestFunc1 failed!" << std::endl;
      return 0;
    }
  
    ::WaitForSingleObject(hThreads,INFINITE);  //等待线程结束
    ::CloseHandle(hThreads);        //关闭线程句柄
    pTest->Release();
    ::CoUninitialize();
    system("pause");
    return 0;
  }
  该段程序将main中定义的ITestInterface1对象,通过指针传到了新建的线程中。运行该段程序,结果如下,又是一串乱序的文字串。也就是说我们需要在TestComObject1中对TestFunc1进行线程同步控制。但大多数人并不想这样做,因为我们开发的组件大多数情况下并不会在多线程执行。但为了避免低概率事件发生后的不良后果,套间出场了。

上一页  2 3 4 5 6 7 8 9 10  下一页

Tags:理解 COM 套间

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接