windows 如何将 Win32 HRESULT 转换为 int 返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1218355/
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 12:55:55  来源:igfitidea点击:

How to convert Win32 HRESULT to int return value?

c++windowswinapi

提问by Brian

I'm writing a Windows console application in C++ and would like to return zero on success and a meaningful error code on failure (i.e., S_OKshould return 0, and E_OUTOFMEMORYshould return a different return value than E_FAILand so on). Is the following an okay approach?:

我正在用 C++ 编写一个 Windows 控制台应用程序,并希望在成功时返回零并在失败时S_OK返回一个有意义的错误代码(即,应该返回 0,并且E_OUTOFMEMORY应该返回E_FAIL与等等不同的返回值)。以下是一种好的方法吗?:

int wmain(int argc, wchar_t *argv[])
{
    HRESULT hr = DoSomething();
    return (int) hr;
}

Or is there a better way? Maybe a standard Win32 API function or macro that I'm forgetting or failing to find?

或者,还有更好的方法?也许是我忘记或找不到的标准 Win32 API 函数或宏?

回答by Paul Mitchell

The OP wants a return value of zero to indicate success. There are success codes which are non-zero and so...

OP 希望返回值为零以表示成功。有非零的成功代码,所以......

if ( SUCCEEDED( hr ) )
    return 0;
return hr;

回答by Steve Gilham

HRESULTis just a 32-bit integer, with each code being a different value, so what you are doing is what you want.

HRESULT只是一个 32 位整数,每个代码都是不同的值,所以你正在做的就是你想要的

回答by Daniel Earwicker

There is an implicit conversion, so the cast is unnecessary.

存在隐式转换,因此不需要强制转换。

(Rather more unfortunately, there is also an implicit conversion to bool, and to the Win32 BOOLtypedef, so S_OKconverts to false and all other values (including errors) convert to true - a common source of errors in COM programs.)

(更不幸的是,还有到bool, 和 Win32 BOOLtypedef的隐式转换,因此S_OK转换为 false 并且所有其他值(包括错误)转换为 true - COM 程序中的常见错误来源。)

回答by GManNickG

The "better way" is to use a C++ style cast:

“更好的方法”是使用 C++ 样式转换:

HRESULT hr = DoSomething();
return static_cast<int>(hr);

Otherwise, like Steve said, it's just an integer. It is defined as a long, not an int, but instead of casting from HRESULTto longto int, you can obviously just do it in one maneuver.

否则,就像史蒂夫说的那样,它只是一个整数。它被定义为 a long,而不是 an int,但不是从HRESULTto转换为longto int,您显然可以在一个操作中完成它。

(That is to say, windows.hmakes the assumption that longwill be a 32-bit integer, which the C & C++ standard's do not guarantee. But that's just how things go, I suppose.)

(也就是说,windows.h假设long将是一个 32 位整数,C 和 C++ 标准不保证这一点。但我想事情就是这样发展的。)



Even better is that this does not require a cast at all.

更好的是,这根本不需要演员表。