Simplest method to create COM object -VC++

Here i am going to write steps that i used to create a object of component and call the functions of that object.
i was just having the progid of that component and i supposed to call the function of that component.
in VB it is very simple to do. u need to just call a function "CreateObject(progID)" and start wrking with that object.
Eg:
ProgId : abc.application.1
dim obj = CreateObject("abc.application.1e");
done.

but in VC++ it is quite complicated to call the function or object creation.
but lets see i have done the task.

required header files:


#include
#include "Objbase.h"

CLSID clsid;
LPUNKNOWN punk;
LPDISPATCH pdisp;
OLECHAR FAR* szMember = _T("GetIpAddress");
DISPID dispid;
DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};

OleInitialize(NULL);// if OLE isn't already loaded.
CLSIDFromProgID(_T("abc.application.1"), &clsid);
CoCreateInstance(clsid, NULL, CLSCTX_SERVER,IID_IUnknown, (LPVOID FAR*)&punk);
punk->QueryInterface(IID_IDispatch, (LPVOID FAR*)&pdisp);
HRESULT hresult = pdisp->GetIDsOfNames(IID_NULL,&szMember , 1, LOCALE_SYSTEM_DEFAULT, &dispid);

VARIANT FAR pVarResult;
HRESULT hresult2 = pdisp->Invoke(dispid,IID_NULL,LOCALE_SYSTEM_DEFAULT,DISPATCH_METHOD,&dispparamsNoArgs, &pVarResult, NULL, NULL);
::MessageBox(NULL,pVarResult.bstrVal,_T("GetIpAddress"),0);
punk->Release();


the above example follow the steps like
1- get clsid of Componet from ProgID by using function

CLSIDFromProgID(_T("abc.application.1"), &clsid);



2 - get the object with outer most interface of the component as IUNKNOWN * (by which all the inner interfaces are derived.
CoCreateInstance(clsid, NULL, CLSCTX_SERVER,IID_IUnknown, (LPVOID FAR*)&punk);


CoCreateInstance is the API that is used to get the interface of the component.
CoCreateInstance involved lots of process of creating the object and getting the iunknown interface.

3.in this step we get the IDisaptch interface to interact with the function of the component.

punk->QueryInterface(IID_IDispatch, (LPVOID FAR*)&pdisp);


here we have used the method queryinterface that is used to query the all inner interface through the outer interface when IID of interface is known.

4. now the most important part that is calling method with dispatch interface.

for this purpose we use two methods :

IDispatch::GetIDsOfNames
IDispatch::Invoke

the first method is used to get the properties and methods of the component.
and second method we used to call the function.

HRESULT hresult = pdisp->GetIDsOfNames(IID_NULL,&szMember , 1,
LOCALE_SYSTEM_DEFAULT, &dispid);
szMember contains the name of method that we are calling here.

here dispid contains the array of the method or property.

then call the invoke method by passing the value of dispid.


more detail about the topic u can find under:







Comments

Popular posts from this blog

XML Programming using IXMLDOMDOCUMENT in vc++

Get correct OS version on win 8.1 without using GetVesionEx API (deprecated )