In Kenny Kerr's msdn magazine articles on imaging and Direct2D he frequently uses HR()
macro.
In his Windows Imaging Component article - http://msdn.microsoft.com/en-gb/magazine/cc500647.aspx
he writes -
Finally, the WIC API makes use of HRESULTs to describe errors. The samples in this article use the HR macro to clearly identify where methods return an HRESULT that needs to be checked. You can replace this with your own error-handling strategy—whether that is throwing an exception or returning the HRESULT yourself.
HR(decoder.CoCreateInstance(CLSID_WICTiffDecoder));
However Kenny doesn't show his definition of HR()
. I am a C++ beginner and am trying to discover and understand the details of the code. I would like to know what his implementation of HR()
is so that I can consider how best to handle the HRESULT
in my program. I have searched to find a definition but there doesn't appear to be source code for these particular articles.
Whilst learning about macros
I have come across these more recent documents that propose the use of inline
functions instead of macros -
http://msdn.microsoft.com/en-us/library/vstudio/ttsbh614.aspx
http://msdn.microsoft.com/en-us/library/vstudio/z8y1yy88.aspx
Can anybody tell me how Kenny defines his HR()
macro? And what it actually does?
How should my Direct2D program handle HRESULT
s? What is the way to make proper use of HRESULT
s so that the program is reliable and resilient?
I am not sure about Kenny's macros, however I suppose that you absolutely need to know the following: error codes have most significant bit set and render the whole value negative. "Standard" macros SUCCEEDED
and FAILED
test codes exactly for this.
HRESULT nValue = ...
if(SUCCEEDED(nValue)) {
// Not Error
}
Then for code brevity and readability you will want a macro that does both things together: tests for success/failure and either returns on error, or throws an exception. I suppose HR
macro in question does one of the two.
If you are going to use ATL, there are predefined macros of this kind already: ATLENSURE_SUCCEEDED
, ATLENSURE_THROW
etc. Microsoft decided to not document them though (I am not aware of a MSDN link to provide here).
Your HR
could be something like (depending on desired action - to throw or exit on error):
inline VOID HR(HRESULT nValue) { if(FAILED(nValue)) AtlThrow(nValue); }
or
#define HR(x) { HRESULT nValue = (x); if(FAILED(nValue)) return nValue; }
Also, to conveniently decode WIC and D2D HRESULT
s you might want to use this system tray helper app.