本記事は、COM Advent Calendar 2014 – Qiitaの7日目の記事です。


前回(QueryInterfaceで増えるオブジェクト)の続きです。

DOMDocumentからQueryInterfaceで2つのIStreamを取り出したときの動きを見てみます。IStream.Readを呼び出してみて、IStream同士は独立して取り扱えるらしいことを確かめてみます。

#include <iostream>
#include <windows.h>
#include <comdef.h>
#include <atlbase.h>
#include <atlutil.h>
 
#import <msxml6.dll>
 
int main()
{
  CoInitializeEx(nullptr, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE);
  try
  {
    MSXML2::IXMLDOMDocumentPtr doc(__uuidof(MSXML2::DOMDocument60));
    if (!doc->loadXML(L"<hoge><piyo/></hoge>"))
    {
      std::clog << "Bad XML!" << std::endl;
      return 1;
    }
 
    IStreamPtr s1 = doc;
    IStreamPtr s2 = doc;
 
    char buf[6];
    ULONG read;
 
    ATLENSURE_SUCCEEDED(s1->Read(buf, sizeof buf, &read));
    std::cout << "s1 read #1: ";
    std::cout.write(buf, read) << std::endl;
 
    ATLENSURE_SUCCEEDED(s2->Read(buf, sizeof buf, &read));
    std::cout << "s2 read #1: ";
    std::cout.write(buf, read) << std::endl;
 
    ATLENSURE_SUCCEEDED(s1->Read(buf, sizeof buf, &read));
    std::cout << "s1 read #2: ";
    std::cout.write(buf, read) << std::endl;
  }
  catch (const _com_error& e)
  {
    std::clog << e.ErrorMessage() << std::endl;
  }
  catch (const ATL::CAtlException& e)
  {
    std::clog << ATL::AtlGetErrorDescription(e) << std::endl;
  }
  CoUninitialize();
}

実行結果はこのとおりです。

s1 read #1: <hoge>
s2 read #1: <hoge>
s1 read #2: <piyo/

2つのIStreamともに1回目のReadでは先頭からのデータが読み出せています。s1とs2は独立して使用できると言って良さそうです。


次回に続きます。


スポンサード リンク

この記事のカテゴリ

  • ⇒ QueryInterfaceで増えるオブジェクト (2)