There are a lot of samples for C#, but only some code snippets for C++ on MSDN. I have put it together and I think it will work, but I am not sure if I am releasing all the COM references I have to.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your code is correct–the reference count on the
IBufferByteAccessinterface of*bufferis incremented by the call toQueryInterface, and you must callReleaseonce to release that reference.However, if you use
ComPtr<T>, this becomes much simpler–withComPtr<T>, you cannot call any of the three members ofIUnknown(AddRef,Release, andQueryInterface); it prevents you from calling them. Instead, it encapsulates calls to these member functions in a way that makes it difficult to screw things up. Here’s an example of how this would look:The call to
bufferInspectable.As(&bufferBytes)performs a safeQueryInterface: it computes the IID from the type ofbufferBytes, performs theQueryInterface, and attaches the resulting pointer tobufferBytes. WhenbufferBytesgoes out of scope, it will automatically callRelease. The code has the same effect as yours, but without the error-prone explicit resource management.The example uses the following two utilities, which help to keep the code clean:
Observant readers will notice that because this code uses a
ComPtrfor theIInspectable*we get frombuffer, this code actually performs an additionalAddRef/Releasecompared to the original code. I would argue that the chance of this impacting performance is minimal, and it’s best to start from code that is easy to verify as correct, then optimize for performance once the hot spots are understood.