C++ – Returning an object as a property in ATL

atlc

I am creating a COM object using Visual Studio 2008 and ATL. Adding simple properties and methods is easy enough but now I want to do something more complicated. I want to give access to a C++ object via a property of my COM object, so I can do something like:

// Pseudo-code
var obj = CreateObject("progid");
obj.aProperty.anotherProperty = someValue;

So, aProperty returns a reference to another object which exposes a property called anotherProperty.

I'm guessing that I need to add another simple ATL object to my project for the second object (call it IClass2), and have something like the following in the IDL:

[propget, id(1)] HRESULT aProperty([out, retval] IClass2** ppValue);

Am I on the right track here? Does anyone know of a good tutorial for this sort of thing?

Best Answer

If you're going to call it from an automation language, you'll need the interface returned to be derived from IDispatch, and you'll likely need to return it at least as an IDispatch**. For retval I think that's good enough; for simple [out] parameters you need to pass it as a VARIANT* (with the variant type set to VT_LPDISPATCH) so that the automation language can understand it.

I'm not sure if there's a good tutorial; it's been a while since I looked for a comprehensive reference. The best advice I could give would be to make sure everything you're passing is automation compatible (eg: is a type which you can put into a VARIANT), and that should take care of 80% of your problems. It's very doable, though; just read up on MSDN and you should be fine.