理解 COM 套间
2006-07-22 22:58:03 来源:WEB开发网四、套间的类型
我们首先看看ATL为我们提供的线程类型:Single,Apartment,Both,Free。我们还是通过例子来说明它们的不同。我们仍然用我们使用刚才实现的TestComObject1来进行测试,先对它实现的唯一方法进行一下说明。
STDMETHODIMP CTestInterface1::TestFunc1()
该方法非常简单,就是打印出该方法运行时,所在的线程的ID号。如果在不同的线程中调用同一个对象的时候,通过套间,发送消息,最终该对象只应该在一个线程中运行,所以它的线程ID号应该是相同的。我们将通过该ID值来验证套间的存在。
{
// TODO: Add your implementation code here
std::cout << "In the itestinferface1''s object, the thread''s id is " << ::GetCurrentThreadId() << std::endl;
return S_OK;
}
1、Single
先来看我们的示例程序(在Code/Apartment/SingleApartment目录下可以找到该工程):
#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;
}
hr = pTest->TestFunc1();
if ( FAILED(hr) )
{
std::cout << "TestFunc1 failed!" << std::endl;
return 0;
}
DWORD threadID;
HANDLE hThreads[1];
hThreads[0] = ::CreateThread(NULL, //创建一个进程
0,
ThreadProc,
(LPVOID)pTest, //将pTest作为一个参数传入新线程
0,
&threadID);
::WaitForSingleObject(hThreads,INFINITE); //等待线程结束
::CloseHandle(hThreads); //关闭线程句柄
pTest->Release();
::CoUninitialize();
system("pause");
return 0;
}
更多精彩
赞助商链接