现在的位置: 首页 > 综合 > 正文

关于套间的第二个程序,疑问多多

2018年04月27日 ⁄ 综合 ⁄ 共 1529字 ⁄ 字号 评论关闭

组件程序十分简单,组件的线程模型为STA,代码如下:

STDMETHODIMP CTheMath::Add(long IOp1, long IOp2, long* plResult)
{
 *plResult = IOp1 + IOp2;
 printf("IOp1 + IOp2 = %d", *plResult);

 return S_OK;
}

调用组件的程序代码如下:

// ATLSTLExe.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <commctrl.h>
#include <iostream>

#include "ATLSTATest.h"
#include "ATLSTATest_i.c"

using namespace  std;

int ExeProc(LPVOID p)
{
 CoInitializeEx(0, COINIT_MULTITHREADED);
 ITheMath *ptrMath;

 HRESULT hr = CoCreateInstance(CLSID_TheMath,
  NULL,
  CLSCTX_SERVER,
  IID_ITheMath,
  (void **)&ptrMath);

 if FAILED(hr)
 {
  cout<<"Get ptrMath error!"<<endl;
  CoUninitialize();
  return -1;
 }

 cout<<"Now Begin to create file!"<<endl;

 long* plresult;
 ptrMath->Add(100, 200, plresult);
 cout<<"100+200 = "<<*plresult<<endl;
 ptrMath->Release();
 CoUninitialize();
 return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
 int i;
 i = 0;
 HANDLE hr;
 DWORD ThreadID;

 hr = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ExeProc, (LPVOID)&i, 0, &ThreadID);

  if (hr)
    CloseHandle(hr);

 MSG msg;
 while (GetMessage(&msg, NULL, 0, 0))
 {
  TranslateMessage(&msg);
  DispatchMessage(&msg);
 }

 return 0;
}

当上述代码中红色部分改为:

CoInitializeEx(0, COINIT_APARTMENTTHREADED);  //STA

程序提示如下调试信息:

加载模块: ATLSTLExe.exe
加载模块: ole32.dll
加载模块: coredll.dll
Get ptrMath error!
线程 'ExeProc' (0xe7a47242) 已退出,返回值为 -1 (0xffffffff)。

当代码不变的时候,com为组件创建一个STA套间,调用组件的程序中创建的线程运行在MTA套间中,对于跨套间的调用,com自动列集接口,实现同步,调试信息如下:

加载模块: ATLSTLExe.exe
加载模块: ole32.dll
加载模块: coredll.dll
加载模块: oleaut32.dll
加载模块: atlstatest.dll
Now Begin to create file!
IOp1 + IOp2 = 300100+200 = 300
卸载模块: atlstatest.dll
卸载模块: oleaut32.dll
线程 'ExeProc' (0x87a1e95a) 已退出,返回值为 0 (0x0)。

以上输出表明程序运行正常,哪位网友能说说原因?

抱歉!评论已关闭.