Another method for using COM components in VC
Http://blog.csdn.net/wqf2)
We know that the most common method in VC is to create a COM component instance through cocreateinstance. Today we will introduce another more flexible method.
First look at the Code:
Hinstance hcominstance=Null;Ic1c*Pic1c=Null;// Load the componentHcominstance=Coloadlibrary(L "calcatlcom. dll",False);If(Hcominstance! =Null){Iclassfactory*Pifacloud=Null;Hresult HR=Cogetclassobject(Clsid_calc,Clsctx_inproc_server,Null,Iid_iclassfactory,(Void**)&Pifacloud);If(Succeeded(HR)){HR=Pifacloud->Createinstance(Null,Iid_ic1c,(Void**)&Pic1c);Pifacloud->Release();}}// Use the component to call the Add method of the pic1c interface to complete the addition operation.If(Pic1c! =Null){Long lresult=Pic1c->Add(3,5);Cstring strmsg;Strmsg.Format("3 + 5 = % d",Lresult);Afxmessagebox(Strmsg);}// Release the componentIf(Hcominstance! =Null){If(Pic1c! =Null){Pic1c->Release();Pic1c=Null;}Cofreelibrary(Hcominstance);}
The code briefly introduces how to load the Component Library to the memory through coloadlibrary when loading the component. Then, you can use cogetclassobject to create a component factory. Finally, you can use the createinstance method of the component factory to create an instance of the component. When releasing a component, release the component instance and then release the component library through cofreelibrary.
The reason for this is that writing is flexible and mainly applies the following situations:
1. to create instances of multiple components in a component library, you can call the createinstance method of the component factory multiple times to create instances of each component in sequence. In this way, we can achieve better efficiency. Cocreateinstance is used to create a component factory every time it is called, which is a waste.
2. If you want to use the permission or permission to access the advanced attributes of a component, you only need to replace iclassfactory with iclassfactory2. Iclassfactory2 is inherited from iclassfactory. The getlicinfo, requestlickey, and createinstancelic methods are used to pass in the correct key or license to access the component legally. Cocreateinstance cannot meet this requirement.