Click here to Skip to main content
15,893,486 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All.

I am trying to use Microsoft Media Foundation to implement a customized media player that would have some functionality that I have not found in other players. I am a newbie when it comes to MF and COM, and am using the book Developing Microsoft Media Foundation Applications from Microsoft Press as a guide.

I understand that MF interacts with COM. The code examples in the book use the CComPtr class to handle reference counting, etc. For example:
C++
CComPtr<IMFTopology> pTopology = NULL;


That being said, not every initialization of a MF object in the book uses this approach. For example, IMFMediaSession. So my question is this: under what circumstances would CComPtr (or AddRef/Release) need to be used in my code? How do I know which interfaces would require this? Strictly speaking, is reference counting mandatory when utilizing COM from my classes? The book does not cover this question to my satisfaction, and I have not been able to find a sufficient answer via MSDN either.

Hopefully my question is clear. Best regards.
Posted
Updated 11-Jan-13 8:24am
v5

1 solution

The crux if the issue is that CComPtr<t> manages this to a large extent, maintaining its own reference and calling AddRef() when created and Release() when destroyed (using the RAII idiom (RAII - Wikipedia[^]). Whenever you hold a pointer to a COM object, generally wrap it in a CComPtr<t> and C++ will correctly managed AddRef/Release for you.

Occasionally, you can use a pointer to the interface directly. For example, if a function you write receives an IMFMediaSession* as a parameter, and the only way you use the parameter is to directly call methods (using -> ), then you don't need to use AddRef/Release (be sure to check for null though).

The main consideration is lifetime of the reference. Always, for example, use CComPtr<t> for:

1. Members of a class or struct, where the sub-object will get destructed (hence Released) when the object is destroyed.
2. In a method, when you invoke another function that may possibly copy the reference (if you're not sure - use CComPtr<t> for safety.

Hope this helps.

(update)
The COM overview is here Component Object Model[^]
Rules for managing reference counts are here: Reference Counts[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900