ptr::ptr

构造 com::ptr 包装 COM 对象。

ptr();
ptr(
   _interface_type * p
);

参数

  • P
    COM 接口指针。

备注

无参数构造函数分配 nullptr 到基础对象处理。 以后对 com::ptr 将验证内部对象和两种方法会失败,直到对象实际创建或附加。

一个参数构造函数添加一个对 COM 对象,但不释放调用方的引用,因此,调用方必须对 COM 对象的 Release 正确放弃控件。 当 entity_CODEcom::ptr 的析构函数调用它在 COM 对象会自动释放它对。

通过 NULL 到此构造函数与调用无参数版本。

示例

本示例实现使用 com::ptr 包装其私有成员 IXMLDOMDocument 对象的 CLR 类。 它演示构造函数的两个版本用法。

// 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::CreateInstance

ptr::~ptr

其他资源

PTR成员