MFC Client for ATL Server
This article explains how to use ATL Server in MFC client.
MyServer is an ATL COM server object DLL called MyServr. It implements a custom interface, IMyServer, which exposes a method called MyMethod.
There are four steps to use an ATL server from an MFC client.
1. Initializing the COM Libraries
Calling AfxOleInit function, which initializes the COM libraries is in the InitInstance function of the application class is the best way to initialize COM.
//Init OLE libraries and support
if (!AfxOleInit())
{
AfxMessageBox("COM initialization failed");
return FALSE;
}
OR
you call
InitializeCOM(NULL);
2. Obtaining the CLSID of a COM Object
If you know the Program ID of the object, CLSIDFromProgID function can be used to convert ProgID to CLSID.
CLSID clsID;
HRESULT hr;
hr= CLSIDFromProgID(OLESTR("MyServr.Object1"), &clsID);
if(FAILED(hr))
{
AfxMessageBox("CLSID Conversion From ProgID failed");
return FALSE;
}
MyServr.Object1 is the program ID of the server.
3. Creating the COM Object
Using import directive is the simplest method to create an object.
#import"D:\VS\MyProjects\MySvr\MyServr.tlb" no_namespace
Now call CreateInstance to create an instance of the object.
CLSID clsID;
HRESULT hr;
//declare smart pointer
IMyServerPtr m_pMyObj;
hr= CLSIDFromProgID(OLESTR("MyServr.Object1"), &clsID);
if(FAILED(hr))
{
AfxMessageBox("CLSID Conversion From ProgID failed");
return FALSE;
}
m_pMyObj.CreateInstance(clsID); //does the work of CoCreateInstance
4. Using the COM Object
Now call interface's method MyMethod.
m_pMyObj->MyMethod();
5. Uninitializing the COM Libraries
In the case of the smart pointer implementation, the cleanup is handled automatically.
OR
Call UnInitialize(); if you have called InitializeCOM() to initialize the COM library.