views:

1050

answers:

1

OK, so I couldn't really think of an apropos title that summarizes this.

The IPrintPipelinePropertyBag interface has the method AddProperty which aptly enough "adds a property to a property bag."

http://msdn.microsoft.com/en-us/library/aa506384.aspx

AddProperty( [in, string] const wchar_t *pszName, [in] const VARIANT *pVar );

We use the following code to add a string to the property bag.

CComVariant varProperty = CComBSTR(someString);
pPrintPropertyBag->AddProperty(L"SOME_PROPERTY", &varFilename);

It's pretty obvious, though, that the CComBSTR and CComVariant that is created goes out of scope after a while. I'm not sure if the PropertyBag handles the string and makes its own copy. Since we can store all kinds of stuff inside a VARIANT, this shouldn't be the case.

Assuming the string isn't handled, my question is, what is the pattern for doing this in COM? How should I pass a VARIANT that contains an allocated string, make that string available for other threads even if the thread that called AddProperty died first, and de-allocate the string properly?

+11  A: 

When you call a COM function with strings or VARIANTs in most cases the only garantuee needed is that those objects are available throughout the call itself. After the call, the object itself is responsible for making copies of the data. For example VARIANT's will most likely use the VariantCopy function that will copy strings, copy COM objects (increases reference count). The only thing you should worry about is when you pass an actual interface in the VARIANT: in that case the interface should be properly reference counted, and QueryInterface, AddRef, and Release should all be implemented accordingly. And don't ever deallocate that object before the reference count reaches 0 ;)

EDIT: Oh, and if you want to learn more about COM programming, be sure to get "Essential COM" by "Don Box". Don Box is the COM guru, and that book will teach you almost anything you would ever want to know about COM and more ;)

Frans-Willem