views:

1104

answers:

3

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?

+7  A: 

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.

Johann Gerell
+2  A: 

This page shows the half of the WinError.h include file that defines FAILED(). It's actually just a very simple macro, the entire definition goes like this:

#define FAILED(Status) ((HRESULT)(Status)<0)
unwind
A: 

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 :)

OregonGhost
Great! but what if the com method i'm calling returns void??What can i test against in this situation?
Adam Naylor
A COM function returning void!? Where? Which one?
Johann Gerell
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
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
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
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
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