CubismLogging.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Copyright(c) Live2D Inc. All rights reserved.
  3. *
  4. * Use of this source code is governed by the Live2D Open Software license
  5. * that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
  6. */
  7. using AOT;
  8. using Live2D.Cubism.Core.Unmanaged;
  9. using System;
  10. using System.Runtime.InteropServices;
  11. using UnityEngine;
  12. namespace Live2D.Cubism.Core
  13. {
  14. /// <summary>
  15. /// Wrapper for core logs.
  16. /// </summary>
  17. public class CubismLogging
  18. {
  19. #region Delegates
  20. /// <summary>
  21. /// Delegate compatible with unmanaged log function.
  22. /// </summary>
  23. /// <param name="message">Message to log.</param>
  24. public unsafe delegate void UnmanagedLogDelegate(char* message);
  25. #endregion
  26. /// <summary>
  27. /// Delegate to pass to native Api.
  28. /// </summary>
  29. // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
  30. public static UnmanagedLogDelegate LogDelegate { get; set; }
  31. #region Initialization
  32. /// <summary>
  33. /// Registers delegates.
  34. /// </summary>
  35. public static unsafe void Initialize(UnmanagedLogDelegate logFunctionDelegate)
  36. {
  37. LogDelegate = logFunctionDelegate;
  38. var logFunction = Marshal.GetFunctionPointerForDelegate(LogDelegate);
  39. CubismCoreDll.SetLogFunction(logFunction);
  40. }
  41. #endregion
  42. /// <summary>
  43. /// Prints an unmanaged, null-terminated message.
  44. /// </summary>
  45. /// <param name="message">Message to log.</param>
  46. [MonoPInvokeCallback(typeof(UnmanagedLogDelegate))]
  47. public static unsafe void LogUnmanaged(char* message)
  48. {
  49. // Marshal message and log it.
  50. var managedMessage = Marshal.PtrToStringAnsi(new IntPtr(message));
  51. Debug.LogFormat("[Cubism] Core: {0}.", managedMessage);
  52. }
  53. /// <summary>
  54. /// Example log function.
  55. /// </summary>
  56. /// <param name="message">Log message.</param>
  57. public static unsafe void InvokeLog(string message)
  58. {
  59. var logFunction = Marshal.GetDelegateForFunctionPointer<UnmanagedLogDelegate>(CubismCoreDll.GetLogFunction());
  60. var str = Marshal.StringToHGlobalAnsi(message);
  61. logFunction.Invoke((char*)str.ToPointer());
  62. }
  63. }
  64. }