Seven is the number.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.0 KiB

4 years ago
  1. using Microsoft.Win32.SafeHandles;
  2. using System;
  3. using System.IO;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using UnityEngine;
  7. namespace Bolt {
  8. public static class ConsoleWriter {
  9. #if UNITY_STANDALONE_WIN
  10. static class PInvoke {
  11. public const int STD_OUTPUT_HANDLE = -11;
  12. [DllImport("kernel32.dll", SetLastError = true)]
  13. static public extern bool AttachConsole(uint dwProcessId);
  14. [DllImport("kernel32.dll", SetLastError = true)]
  15. static public extern bool AllocConsole();
  16. [DllImport("kernel32.dll", SetLastError = true)]
  17. static public extern bool FreeConsole();
  18. [DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  19. static public extern IntPtr GetStdHandle(int nStdHandle);
  20. [DllImport("kernel32.dll")]
  21. static public extern bool SetConsoleTitle(string lpConsoleTitle);
  22. }
  23. static TextWriter realOut;
  24. #endif
  25. public static void Open() {
  26. #if UNITY_STANDALONE_WIN
  27. if (realOut == null) {
  28. realOut = Console.Out;
  29. }
  30. var hasConsole = PInvoke.AttachConsole(0x0ffffffff);
  31. if (hasConsole == false) {
  32. PInvoke.AllocConsole();
  33. }
  34. try {
  35. // grab handle ptr
  36. var outHandlePtr = PInvoke.GetStdHandle(PInvoke.STD_OUTPUT_HANDLE);
  37. // we can then create a filestream from this handle
  38. #pragma warning disable 0618
  39. var fileStream = new FileStream(outHandlePtr, FileAccess.Write);
  40. #pragma warning restore 0618
  41. // and then create a new stream writer (using ASCII)
  42. var stdOut = new StreamWriter(fileStream, Encoding.ASCII);
  43. stdOut.AutoFlush = true;
  44. // and force unity to use this
  45. Console.SetOut(stdOut);
  46. }
  47. catch (System.Exception e) {
  48. Debug.Log(e);
  49. }
  50. #endif
  51. }
  52. public static void Close() {
  53. #if UNITY_STANDALONE_WIN
  54. PInvoke.FreeConsole();
  55. Console.SetOut(realOut);
  56. realOut = null;
  57. #endif
  58. }
  59. }
  60. }