Another way to use COM components in VC

zhaozj2021-02-16  132

Another way to use COM components in VC

(http://blog.9cbs.net/wqf2)

We know that the most commonly used in VC is an instance of COM components through CocreateInstance. Today we introduce another more flexible way. First see the code:

Hinstance hCominstance = NULL;

Icalc * picalc = null;

// Loading the component

HCominstance = COLOADLIBRARY (L "Calcatlcom.dll", False);

IF (HCominstance! = NULL)

{

IClassFactory * pifactory = null;

HRESULT HR = COGETCLASSOBJECT (CLSID_CALC, CLSCTX_INPROC_SERVER, NULL, IID_ICLASSFAACTORY, (VOID **) & PIFACTORY

En (ac))

{

HR = Pifactory-> CreateInstance (NULL, IID_ICALC, (VOID **) & picalc);

Pifactory-> Release ();

}

}

// Use the component to call the Add method of the PICAlC interface complete the addition operation.

IF (picalc! = null)

{

Long Lresult = picalc-> add (3,5);

CString strmsg;

Strmsg.Format ("3 5 =% D", LRESULT);

AfxMessageBox (STRMSG);

}

// Release component

IF (HCominstance! = NULL)

{

IF (picalc! = null)

{

Picalc-> Release ();

Picalc = NULL;

}

COFREELIBRARY (HCominstance);

}

To briefly introduce the code, load the component library into memory through COLOADLIBRAR while loading the component, and then creates a component factory through the CogetherClassObject, and finally create an instance of the component through the CREATEINSTANCE method of the component factory. When the component is released, the component instance is released first, then release the component library through the COFREELIBRARY. The reason why it is said that it is more flexible, mainly to apply several situations: 1. When you want to create a plurality of components in a component library, only one component factory instance is created, you can call the CreateInstance method for multiple calling components. To create an instance of each component sequentially. Do this can achieve better efficiency. Create with CocreateInstance, create a component factory per call, some waste. 2. When you want to use the advanced properties of the license or permission to access the component, you only need to change the iClassFactory to iClassFactory2. IclassFactory2 inherits from iClassFactory, multiple getLicinfo, Requestlickey, CreateInstanceLic, to pass the correct key or license to legally access the component. And CocreateInstance cannot meet this requirement.

转载请注明原文地址:https://www.9cbs.com/read-8635.html

New Post(0)