简体   繁体   English

在C ++ / CLI中实例化COM对象

[英]COM object instantiate in C++/CLI

I am new to Managed C++/Cli; 我是Managed C ++ / Cli的新手。 I have one legacy COM DLL, and I have imported the DLL in C++/CLI class, but I am not sure how to create an instance of the COM object and use it. 我有一个旧版COM DLL,并且已经在C ++ / CLI类中导入了DLL,但是我不确定如何创建COM对象的实例并使用它。

Can anyone help with this? 有人能帮忙吗?

If it is properly registered simply try: 如果已正确注册,请尝试:

Type typeOfCOMObject = Type.GetTypeFromProgID("COMProject.COMClass");
object instanceOfCOMObject = Activator.CreateObject(typeOfCOMObject);

Then use cast or reflection to access the object's methods. 然后使用强制转换或反射来访问对象的方法。

There are several ways to access COM objects from C++/CLI. 有几种方法可以从C ++ / CLI访问COM对象。

The easiest way is to let the .Net runtime create a managed wrapper for the COM object like natorion describes in his answer. 最简单的方法是让.Net运行时为COM对象创建托管包装,如natorion在其答案中描述的那样。 For this to work you need to generate an interop assembly in Visual Studio or using the tlbimp.exe command. 为此,您需要在Visual Studio中或使用tlbimp.exe命令生成一个互操作程序集。 This is the same as you do in other .Net languages like C# and VB.Net. 这与使用其他.Net语言(如C#和VB.Net)相同。

Another way is to use the #import directive to generate a native wrapper. 另一种方法是使用#import指令生成本机包装。 This is the best way if the COM object uses a lot of native structs which are difficult to marshal to .Net or if you need to control the object lifetime. 如果COM对象使用大量本机结构,这些结构很难编组到.Net或需要控制对象生存期,则这是最佳方法。

IYourComObject obj;
obj.CreateInstance("YourComObject"); 

(There are other overloads of CreateInstance) (CreateInstance还有其他重载)

A third way is to ignore all generated wrappers hand create the object manually. 第三种方法是忽略所有生成的包装器,手动创建对象。 This is the most advanced and difficult way where you have complete control. 这是您可以完全控制的最先进,最困难的方法。

CoCreateInstanceEx(__uuidof(yourcomobject), NULL, CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER, NULL, 1, &instance)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM