windows 有人可以解释 C++ FAILED 函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/377322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 11:44:50  来源:igfitidea点击:

Can someone explain the c++ FAILED function?

c++windowscom

提问by Adam Naylor

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?

我看过很多示例 C++ 代码,它们将函数调用包装在 FAILED() 函数/方法/宏中。有人可以向我解释这是如何工作的吗?如果可能的话,有人知道 ac# 等效吗?

回答by Johann Gerell

It generally checks COM function errors. But checking any function that returns a HRESULTis what it's meant for, specifically. FAILEDreturns a true value if the HRESULTvalue is negative, which means that the function failed ("error" or "warning" severity). Both S_OKand S_FALSEare >= 0 and so they are not used to convey an error. With "negative" I mean that the high bit is set for HRESULTerror codes, i.e., their hexadecimal representation, which can be found in, e.g., winerror.h, begins with an 8, as in 0x8000FFFF.

它通常会检查 COM 函数错误。但是检查任何返回 a 的函数HRESULT就是它的意思,特别是。FAILED如果HRESULT值为负,则返回真值,这意味着函数失败(“错误”或“警告”严重性)。两个S_OKS_FALSE是> = 0,因此它们不被用于传达错误。对于“负”,我的意思是为HRESULT错误代码设置高位,它们的十六进制表示,可以在例如winerror.h 中找到,以 8 开头,如 0x8000FFFF。

回答by unwind

This pageshows 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:

此页面显示了 WinError.h 包含文件的一半,该文件定义了FAILED(). 它实际上只是一个非常简单的宏,整个定义是这样的:

#define FAILED(Status) ((HRESULT)(Status)<0)

回答by OregonGhost

And if possible does anyone know a c# equivalent?

如果可能的话,有人知道 ac# 等效吗?

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.

在 C# 中实际上不需要它,除非您使用 COM 对象。大多数 .NET 函数要么已经返回(或多或少)有意义的值(即 null、false),要么在失败时抛出异常。

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.

如果您直接访问 COM 对象,您可以定义一个简单的 Failed 函数,该函数执行 unwind 帖子中的宏所做的工作。在本地定义(受保护/私有),因为杂乱的 COM 详细信息无论如何都不应该在您的应用程序中可见。

In case you didn't know, there's also a SUCCEEDED macro in COM. No need to test for failure :)

如果您不知道,COM 中还有一个 SUCCEEDED 宏。无需测试失败:)