次の方法で共有


ptr::ptr

COM オブジェクトをラップするための com::ptr を構築します。

ptr();
ptr(
   _interface_type * p
);

パラメータ

  • P
    COM インターフェイス ポインタ。

解説

引数を持たないコンストラクタは、基になるオブジェクト ハンドルに nullptr を代入します。com::ptr への以降の呼び出しでは、内部オブジェクトが検証され、オブジェクトが実際に作成されるかアタッチされるまで、エラーなしで失敗します。

1 つの引数のコンストラクタは、COM オブジェクトへの参照を追加しますが、呼び出し元の参照を解放しません。したがって、呼び出し元では真に制御を放棄するために COM オブジェクトに対する Release を呼び出す必要があります。com::ptr のデストラクタを呼び出すと、COM オブジェクトに対する参照が自動的に解放されます。

このコンストラクタに NULL を渡した場合は、引数を持たないコンストラクタを呼び出したときと同じです。

使用例

この例では、プライベート メンバ IXMLDOMDocument オブジェクトをラップするために com::ptr を使用する CLR クラスを実装します。また、前述の 2 バージョンのコンストラクタの使用方法を示します。

// comptr_ptr.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);   
   }

   // construct the internal com::ptr with a COM object
   XmlDocument(IXMLDOMDocument* pDoc) : m_ptrDoc(pDoc) {}

   // 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;
};

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

   try {
      // create an XML DOM document object
      Marshal::ThrowExceptionForHR(CoCreateInstance(CLSID_DOMDocument30, NULL, 
         CLSCTX_ALL, IID_IXMLDOMDocument, (void**)&pDoc));
      // construct the ref class with the COM object
      XmlDocument doc1(pDoc);

      // or create the class from a progid string
      XmlDocument doc2("Msxml2.DOMDocument.3.0");
   }
   // doc1 and doc2 destructors are called when they go out of scope
   // and the internal com::ptr releases its reference to the COM object
   catch (Exception^ e) {
      Console::WriteLine(e);   
   }
   finally {
      if (NULL != pDoc) {
         pDoc->Release();      
      }
   }
}

必要条件

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

名前空間 msclr::com

参照

概念

ptr Members

ptr::CreateInstance

ptr::~ptr