次の方法で共有


ptr::Detach

COM オブジェクトの所有権を放棄し、オブジェクトへのポインタを返します。

_interface_type * Detach();

戻り値

COM オブジェクトへのポインタ。

オブジェクトが所有されていない場合は NULL を返します。

例外

内部的には、所有されている COM オブジェクト上の QueryInterface が呼び出され、エラー HRESULT が ThrowExceptionForHR によって例外に変換されます。

解説

Detach は、最初に、呼び出し元のために COM オブジェクトへの参照を追加し、次に com::ptr により所有されているすべての参照を解放します。呼び出し元は最終的に、返されたオブジェクトを解放して破棄する必要があります。

使用例

この例では、プライベート メンバ IXMLDOMDocument オブジェクトをラップするために com::ptr を使用する CLR クラスを実装します。DetachDocument メンバ関数は、Detach を呼び出して COM オブジェクトの所有権を放棄し、呼び出し元にポインタを返します。

// comptr_detach.cpp
// compile with: /clr /link msxml2.lib
#include <msxml2.h>
#include <msclr\com\ptr.h>

#import <msxml3.dll> raw_interfaces_only

using namespace System;
using namespace System::Runtime::InteropServices;
using namespace msclr;

// a ref class that uses a com::ptr to contain an 
// IXMLDOMDocument object
ref class XmlDocument {
public:
   // construct the internal com::ptr with a null interface
   // and use CreateInstance to fill it
   XmlDocument(String^ progid) {
      m_ptrDoc.CreateInstance(progid);   
   }

   // detach the COM object and return it
   // this releases the internal reference to the object
   IXMLDOMDocument* DetachDocument() {
      return m_ptrDoc.Detach();
   }

   // note that the destructor will call the com::ptr destructor
   // and automatically release the reference to the COM object

private:
   com::ptr<IXMLDOMDocument> m_ptrDoc;
};

// unmanaged function that loads XML into a raw XML DOM Document object
HRESULT LoadXml(IXMLDOMDocument* pDoc, BSTR bstrXml) {
   HRESULT hr = S_OK;
   VARIANT_BOOL bSuccess;
   hr = pDoc->loadXML(bstrXml, &bSuccess);
   if (S_OK == hr && !bSuccess) {
      hr = E_FAIL;
   }
   return hr;
}


// use the ref class to handle an XML DOM Document object
int main() {
   IXMLDOMDocument* pDoc = NULL;
   BSTR bstrXml = NULL;

   try {
      // create the class from a progid string
      XmlDocument doc("Msxml2.DOMDocument.3.0");

      bstrXml = ::SysAllocString(L"<word>persnickety</word>");
      if (NULL == bstrXml) {
         throw gcnew OutOfMemoryException("bstrXml");
      }
      // detach the document object from the ref class
      pDoc = doc.DetachDocument();
      // use unmanaged function and raw object to load xml
      Marshal::ThrowExceptionForHR(LoadXml(pDoc, bstrXml));
      // release document object as the ref class no longer owns it
      pDoc->Release();
      pDoc = NULL;
   }
   catch (Exception^ e) {
      Console::WriteLine(e);   
   }
   finally {
      if (NULL != pDoc) {
         pDoc->Release();
      }
      
   }
}

必要条件

ヘッダー ファイル <msclr\com\ptr.h>

名前空間 msclr::com

参照

概念

ptr Members

ptr::Release

ptr::Attach