I've seen a lot of example c++ code that wraps function calls in a FAILED() function/method/macro. Could someone explain to me how this works? And if possible does anyone know a c# equivalent?
3 Answers
It generally checks COM function errors. But checking any function that returns a HRESULT
is what it's meant for, specifically. FAILED
returns a true value if the HRESULT
value is negative, which means that the function failed ("error" or "warning" severity). Both S_OK
and S_FALSE
are >= 0 and so they are not used to convey an error. With "negative" I mean that the high bit is set for HRESULT
error codes, i.e., their hexadecimal representation, which can be found in, e.g., winerror.h, begins with an 8, as in 0x8000FFFF.

- 24,991
- 10
- 72
- 122
And if possible does anyone know a c# equivalent?
You won't actually need that in C#, unless you're using COM objects. Most .NET functions either already return a (more or less) meaningful value (i.e. null, false) or throw an exception when they fail.
If you're directly accessing a COM object, you can define a simple Failed function that does what the macro in unwind's post does. Define that locally (protected/private), since the messy COM details shouldn't be visible in your app anyway.
In case you didn't know, there's also a SUCCEEDED macro in COM. No need to test for failure :)

- 23,359
- 7
- 71
- 108
-
Great! but what if the com method i'm calling returns void?? What can i test against in this situation? – Adam Naylor Dec 18 '08 at 10:25
-
A COM function returning void!? Where? Which one? – Johann Gerell Dec 18 '08 at 10:30
-
Am i right in thinking the managed directx library is in fact a com wrapper? or am i completely mistaken? (as almost every method returns void!!) – Adam Naylor Dec 18 '08 at 10:52
-
MDX, if I remember correctly, should not be used anymore. You may want to try XNA instead. Anyway, a function returning void most likely signals failure by throwing an exception instead. – OregonGhost Dec 18 '08 at 13:11
-
MDX is a thin COM wrapper. So it hides actual COM details while remaining roughly equivalent to it, that may be the reason why the methods return void. – OregonGhost Dec 18 '08 at 13:13
-
That makes sense! Regarding the XNA comment... i feel dirty enough using managed directx so i wouldn't want to take the plunge and use a 'toy' such as XNA ;) – Adam Naylor Dec 18 '08 at 15:59
-
XNA is not really a toy. There are impressive demos out in the wild (on youtube, for example), and it even runs on XBox 360. And trust me, it's a lot more fun than MDX. – OregonGhost Dec 19 '08 at 10:17