potisanのプログラミングメモ

趣味のプログラマーがプログラミング関係で気になったことや調べたことをいつでも忘れられるようにメモするブログです。はてなブログ無料版なので記事の上の方はたぶん広告です。記事中にも広告挿入されるみたいです。

C# HRESULTからWin32エラーコードへ変換する関数群

namespace ConsoleApp1
{
    class Program
    {
        static void Main()
        {
            const int hr = unchecked((int)0x8007007a);
            var facility = Utility.GetHRFacility(hr);
            var win32errcode = Utility.GetWin32ErrorCodeFromHR(hr);
        }
    }

    public static partial class Utility
    {
        public static short GetHRFacility(int hr)
        {
            return unchecked((short)((((uint)hr) >> 16) & 0x1fff));
        }

        public static bool IsHRFacilityWin32(int hr)
        {
            const int FACILITY_WIN32 = 7;
            return ((((uint)hr) >> 16) & 0x1fff) == FACILITY_WIN32;
        }

        public static int GetHRFromWin32ErrorCode(int code)
        {
            const int FACILITY_WIN32 = 7;
            if (code <= 0)
                return code;
            else
                return unchecked((int)(((uint)code & 0xffffu) | (FACILITY_WIN32 << 16) | 0x80000000u));
        }

        public static int? GetWin32ErrorCodeFromHR(int hr)
        {
            const int FACILITY_WIN32 = 7;
            var facility = (((uint)hr) >> 16) & 0x1fff;
            if (facility != FACILITY_WIN32)
                return null;
            return hr & 0xffff;
        }
    }
}

2021/3/10:この記事は別のブログで投稿した記事を移動したものです。