HOWTO: Get a C++ Class from an Interface Pointer in ATL

ID: Q234785


The information in this article applies to:


SUMMARY

When writing an ATL-based COM server, you may end up with a pointer to a specific interface implemented in the server; however, you may want to access the C++ class from the server that implements that interface.

Because of the overhead, ATL does not maintain maps or lists of running objects. Because a server could contain many different objects of the same type, finding the C++ class from the COM interface implementation requires extra work on the part of the programmer.


MORE INFORMATION

One of the easiest and safest methods to accomplish this "mapping" is to use ATL's COM map and QueryInterface. By placing a pointer to the C++ class into the COM map, you can safely get the pointer to the object by calling the QueryInterface method.

To implement this solution, use the COM_INTERFACE_ENTRY_IID macro and the CLSID for the object found in the .idl file:


BEGIN_COM_MAP(CMyAtlObj)
   COM_INTERFACE_ENTRY_IID(CLSID_MyAtlObj, CMyAtlObj)
   // ... other COM_INTERFACE_ENTRY macros
END_COM_MAP() 
At this point you can get a pointer to that class by calling QueryInterface() and accessing public members of it:


	CMyAtlObj* pObj;
	
	if (!SUCCEEDED(pUnk->QueryInterface(CLSID_MyAtlObj, (void **)&pObj)))
		return NULL;

	hReturn = pObj->Method1(); //Method1 is a public member function of CMyAtlObj class.
	pObj->Release(); //Needed because we called QueryInterface.

	return hReturn;
} 
NOTE: It is not possible to access the C++ class from outside the server that it is being implemented inside without exporting the class methods. This method is not advised for COM servers because it breaks the COM model, because the application would need to be written to use that particular server. This method will fail if the pointer to the object needs to be marshaled.

© Microsoft Corporation 1999, All Rights Reserved.
Contributions by Kelly Marie Ward, Microsoft Corporation

Additional query words:


Keywords          : kbATL210 kbCOMt kbVC500 kbVC600 kbATL300 kbDSupport kbGrpMFCATL kbArchitecture 
Version           : WINDOWS:2.1,3.0
Platform          : WINDOWS 
Issue type        : kbhowto 

Last Reviewed: July 21, 1999