简体   繁体   中英

COM object instantiate in C++/CLI

I am new to 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.

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.

The easiest way is to let the .Net runtime create a managed wrapper for the COM object like natorion describes in his answer. For this to work you need to generate an interop assembly in Visual Studio or using the tlbimp.exe command. This is the same as you do in other .Net languages like C# and VB.Net.

Another way is to use the #import directive to generate a native wrapper. 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.

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

(There are other overloads of 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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