创建 COM 对象的实例。 com::ptr。
void CreateInstance(
System::String ^ progid,
LPUNKNOWN pouter,
DWORD cls_context
);
void CreateInstance(
System::String ^ progid,
LPUNKNOWN pouter
);
void CreateInstance(
System::String ^ progid
);
void CreateInstance(
const wchar_t * progid,
LPUNKNOWN pouter,
DWORD cls_context
);
void CreateInstance(
const wchar_t * progid,
LPUNKNOWN pouter
);
void CreateInstance(
const wchar_t * progid
);
void CreateInstance(
REFCLSID rclsid,
LPUNKNOWN pouter,
DWORD cls_context
);
void CreateInstance(
REFCLSID rclsid,
LPUNKNOWN pouter
);
void CreateInstance(
REFCLSID rclsid
);
参数
progid
ProgID 字符串。pouter
对复合对象的 IUnknown 接口 (控件 IUnknown) 的指针。如果 pouter 未指定,则使用 NULL 。cls_context
代码管理新创建的对象上运行的上下文。值从 CLSCTX 枚举中采用。如果 cls_context 未指定,则使用该值 CLSCTX_ALL。rclsid
CLSID 与将用于创建对象的数据和代码。
异常
如果 com::ptr 已拥有对 COM 对象, CreateInstance 引发 InvalidOperationException。
此函数调用 CoCreateInstance 并使用 ThrowExceptionForHR 将所有错误 HRESULT 转换为适当的异常。
备注
CreateInstance 使用 CoCreateInstance 创建指定的对象的新实例,标识从 ProgID 或 CLSID。com::ptr 引用新创建的对象,并自动释放所有拥有对损坏。
示例
本示例实现使用 com::ptr 包装其私有成员 IXMLDOMDocument 对象的 CLR 类。类构造函数使用 CreateInstance 的两种不同形式创建文档对象从 ProgID 或某 CLSID 以及 CLSCTX。
// comptr_createinstance.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);
}
XmlDocument(REFCLSID clsid, DWORD clsctx) {
m_ptrDoc.CreateInstance(clsid, NULL, clsctx);
}
// 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() {
try {
// create the class from a progid string
XmlDocument doc1("Msxml2.DOMDocument.3.0");
// or from a clsid with specific CLSCTX
XmlDocument doc2(CLSID_DOMDocument30, CLSCTX_INPROC_SERVER);
}
catch (Exception^ e) {
Console::WriteLine(e);
}
}
要求
头文件 <msclr \ COM \ ptr.h>
命名空间 msclr::com