output a more helpful error message on windows for GetErrorMessage

This commit is contained in:
CasualPokePlayer 2022-08-29 16:33:41 -07:00
parent 06226e78cf
commit e198122691
1 changed files with 27 additions and 2 deletions

View File

@ -3,6 +3,7 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using BizHawk.Common.StringExtensions;
@ -147,8 +148,24 @@ namespace BizHawk.Common
private static extern bool FreeLibrary(IntPtr hModule); // return type was annotated MarshalAs(UnmanagedType.Bool)
[DllImport("kernel32.dll")]
private static extern uint GetLastError();
private static extern uint GetLastError();
private enum FORMAT_MESSAGE : uint
{
ALLOCATE_BUFFER = 0x00000100,
ARGUMENT_ARRAY = 0x00002000,
FROM_HMODULE = 0x00000800,
FROM_STRING = 0x00000400,
FROM_SYSTEM = 0x00001000,
IGNORE_INSERTS = 0x00000200,
}
[DllImport("kernel32.dll")]
private static extern int FormatMessageA(FORMAT_MESSAGE flags, IntPtr source, uint messageId, uint languageId, out IntPtr outMsg, int size, IntPtr args);
[DllImport("kernel32.dll")]
private static extern IntPtr LocalFree(IntPtr hMem); // use this to free a message from FORMAT_MESSAGE.ALLOCATE_BUFFER
[DllImport("kernel32.dll", SetLastError = true)] // had BestFitMapping = false, ThrowOnUnmappableChar = true
private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); // param procName was annotated `[MarshalAs(UnmanagedType.LPStr)]`
@ -173,7 +190,15 @@ namespace BizHawk.Common
return ret != IntPtr.Zero ? ret : throw new InvalidOperationException($"got null pointer from {nameof(LoadLibrary)}, error code: {GetLastError()}");
}
public string GetErrorMessage() => $"Error Code 0x{GetLastError():X8}";
public string GetErrorMessage()
{
var errCode = GetLastError();
var sz = FormatMessageA(FORMAT_MESSAGE.ALLOCATE_BUFFER | FORMAT_MESSAGE.FROM_SYSTEM | FORMAT_MESSAGE.IGNORE_INSERTS,
IntPtr.Zero, errCode, 0, out var buffer, 1024, IntPtr.Zero);
var ret = Marshal.PtrToStringAnsi(buffer, sz);
_ = LocalFree(buffer);
return ret;
}
}
public enum DistinctOS : byte