简体   繁体   中英

How to convert Win32 HRESULT to int return value?

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

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?

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

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

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

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 BOOL typedef, so S_OK converts to false and all other values (including errors) convert to true - a common source of errors in COM programs.)

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

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 HRESULT to long to int , you can obviously just do it in one maneuver.

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM